mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
7b638dac6b | ||
![]() |
6db79cef86 | ||
![]() |
0454e8d869 | ||
![]() |
0aa1afee7a |
16
README.md
16
README.md
@@ -1,9 +1,8 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
|
||||

|
||||
|
||||
_Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
@@ -41,18 +40,13 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.cyou/) | [](https://www.napcat.wiki) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| QQ Group | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/8zJMLjqy2Y) | [](https://qm.qq.com/q/HaRcfrHpUk) | [](https://qm.qq.com/q/I6LU87a0Yq) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Telegram | [](https://t.me/MelodicMoonlight) |
|
||||
|:-:|:-:|
|
||||
| Contact | [](https://qm.qq.com/q/I6LU87a0Yq) | [](https://qm.qq.com/q/HaRcfrHpUk) | [](https://t.me/MelodicMoonlight) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
## Thanks
|
||||
|
||||
+ [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||
|
||||
+ [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
||||
|
||||
+ 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||
|
||||
---
|
||||
@@ -64,3 +58,7 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
|
||||
|
||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||
|
||||
## Warnings
|
||||
|
||||
[某框架抄袭部分分析](https://napneko.github.io/other/about-copy)
|
||||
|
BIN
external/LiteLoaderWrapper.zip
vendored
BIN
external/LiteLoaderWrapper.zip
vendored
Binary file not shown.
BIN
external/logo.png
vendored
BIN
external/logo.png
vendored
Binary file not shown.
Before Width: | Height: | Size: 250 KiB After Width: | Height: | Size: 204 KiB |
Binary file not shown.
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "qq-chat",
|
||||
"version": "9.9.19-34740",
|
||||
"verHash": "f31348f2",
|
||||
"linuxVersion": "3.2.17-34740",
|
||||
"linuxVerHash": "5aa2d8d6",
|
||||
"version": "9.9.18-32869",
|
||||
"verHash": "e735296c",
|
||||
"linuxVersion": "3.2.16-32869",
|
||||
"linuxVerHash": "4c192ba9",
|
||||
"private": true,
|
||||
"description": "QQ",
|
||||
"productName": "QQ",
|
||||
@@ -16,10 +16,27 @@
|
||||
"bin": {
|
||||
"qd": "externals/devtools/cli/index.js"
|
||||
},
|
||||
"appid": {
|
||||
"win32": "537258389",
|
||||
"darwin": "537258412",
|
||||
"linux": "537258424"
|
||||
},
|
||||
"main": "./loadNapCat.js",
|
||||
"buildVersion": "34740",
|
||||
"peerDependenciesMeta": {
|
||||
"*": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"pnpm": {
|
||||
"patchedDependencies": {
|
||||
"@vue/runtime-dom@3.5.12": "patches/@vue__runtime-dom@3.5.12.patch",
|
||||
"@swc/helpers@0.5.3": "patches/@swc__helpers@0.5.3.patch",
|
||||
"vuex@4.1.0": "patches/vuex@4.1.0.patch"
|
||||
}
|
||||
},
|
||||
"buildVersion": "32869",
|
||||
"isPureShell": true,
|
||||
"isByteCodeShell": true,
|
||||
"platform": "win32",
|
||||
"eleArch": "x64"
|
||||
}
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "4.7.55",
|
||||
"version": "4.7.43",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "4.7.55",
|
||||
"version": "4.7.43",
|
||||
"scripts": {
|
||||
"build:universal": "npm run build:webui && vite build --mode universal || exit 1",
|
||||
"build:framework": "npm run build:webui && vite build --mode framework || exit 1",
|
||||
@@ -41,6 +41,7 @@
|
||||
"ajv": "^8.13.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"commander": "^13.0.0",
|
||||
"compressing": "^1.10.1",
|
||||
"cors": "^2.8.5",
|
||||
"esbuild": "0.25.0",
|
||||
"eslint": "^9.14.0",
|
||||
@@ -53,16 +54,16 @@
|
||||
"image-size": "^1.1.1",
|
||||
"json5": "^2.2.3",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"napcat.protobuf": "^1.1.4",
|
||||
"typescript": "^5.3.3",
|
||||
"typescript-eslint": "^8.13.0",
|
||||
"vite": "^6.0.1",
|
||||
"vite-plugin-cp": "^6.0.0",
|
||||
"vite-tsconfig-paths": "^5.1.0",
|
||||
"napcat.protobuf": "^1.1.4",
|
||||
"winston": "^3.17.0",
|
||||
"compressing": "^1.10.1"
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@napi-rs/canvas": "^0.1.69",
|
||||
"express": "^5.0.0",
|
||||
"silk-wasm": "^3.6.1",
|
||||
"ws": "^8.18.0"
|
||||
|
BIN
src/canvas/image/normal/01.jpg
Normal file
BIN
src/canvas/image/normal/01.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.3 MiB |
BIN
src/canvas/image/normal/02.jpg
Normal file
BIN
src/canvas/image/normal/02.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.3 MiB |
BIN
src/canvas/image/normal/03.jpg
Normal file
BIN
src/canvas/image/normal/03.jpg
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.3 MiB |
@@ -145,8 +145,8 @@ export enum FileUriType {
|
||||
|
||||
export async function checkUriType(Uri: string) {
|
||||
const LocalFileRet = await solveProblem((uri: string) => {
|
||||
if (fs.existsSync(path.normalize(uri))) {
|
||||
return { Uri: path.normalize(uri), Type: FileUriType.Local };
|
||||
if (fs.existsSync(uri)) {
|
||||
return { Uri: uri, Type: FileUriType.Local };
|
||||
}
|
||||
return undefined;
|
||||
}, Uri);
|
||||
|
@@ -1 +1 @@
|
||||
export const napCatVersion = '4.7.55';
|
||||
export const napCatVersion = '4.7.43';
|
||||
|
@@ -28,8 +28,6 @@ import { SendMessageContext } from '@/onebot/api';
|
||||
import { getFileTypeForSendType } from '../helper/msg';
|
||||
import { FFmpegService } from '@/common/ffmpeg';
|
||||
import { rkeyDataType } from '../types/file';
|
||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { FileId } from '../packet/transformer/proto/misc/fileid';
|
||||
|
||||
export class NTQQFileApi {
|
||||
context: InstanceContext;
|
||||
@@ -65,76 +63,6 @@ export class NTQQFileApi {
|
||||
}
|
||||
}
|
||||
|
||||
async getFileUrl(chatType: ChatType, peer: string, fileUUID?: string, file10MMd5?: string | undefined) {
|
||||
if (this.core.apis.PacketApi.available) {
|
||||
try {
|
||||
if (chatType === ChatType.KCHATTYPEGROUP && fileUUID) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetGroupFileUrl(+peer, fileUUID);
|
||||
} else if (file10MMd5 && fileUUID) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetPrivateFileUrl(peer, fileUUID, file10MMd5);
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
||||
}
|
||||
}
|
||||
throw new Error('fileUUID or file10MMd5 is undefined');
|
||||
}
|
||||
|
||||
async getPttUrl(peer: string, fileUUID?: string) {
|
||||
if (this.core.apis.PacketApi.available && fileUUID) {
|
||||
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
|
||||
try {
|
||||
if (appid && appid === 1403) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetGroupPttUrl(+peer, {
|
||||
fileUuid: fileUUID,
|
||||
storeId: 1,
|
||||
uploadTime: 0,
|
||||
ttl: 0,
|
||||
subType: 0,
|
||||
});
|
||||
} else if (fileUUID) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetPttUrl(peer, {
|
||||
fileUuid: fileUUID,
|
||||
storeId: 1,
|
||||
uploadTime: 0,
|
||||
ttl: 0,
|
||||
subType: 0,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
||||
}
|
||||
}
|
||||
throw new Error('packet cant get ptt url');
|
||||
}
|
||||
|
||||
async getVideoUrlPacket(peer: string, fileUUID?: string) {
|
||||
if (this.core.apis.PacketApi.available && fileUUID) {
|
||||
let appid = new NapProtoMsg(FileId).decode(Buffer.from(fileUUID.replaceAll('-', '+').replaceAll('_', '/'), 'base64')).appid;
|
||||
try {
|
||||
if (appid && appid === 1415) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetGroupVideoUrl(+peer, {
|
||||
fileUuid: fileUUID,
|
||||
storeId: 1,
|
||||
uploadTime: 0,
|
||||
ttl: 0,
|
||||
subType: 0,
|
||||
});
|
||||
} else if (fileUUID) {
|
||||
return this.core.apis.PacketApi.pkt.operation.GetVideoUrl(peer, {
|
||||
fileUuid: fileUUID,
|
||||
storeId: 1,
|
||||
uploadTime: 0,
|
||||
ttl: 0,
|
||||
subType: 0,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
this.context.logger.logError('获取文件URL失败', (error as Error).message);
|
||||
}
|
||||
}
|
||||
throw new Error('packet cant get video url');
|
||||
}
|
||||
|
||||
async copyFile(filePath: string, destPath: string) {
|
||||
await this.core.util.copyFile(filePath, destPath);
|
||||
@@ -397,7 +325,6 @@ export class NTQQFileApi {
|
||||
}
|
||||
});
|
||||
});
|
||||
return res.flat();
|
||||
}
|
||||
|
||||
async downloadMedia(msgId: string, chatType: ChatType, peerUid: string, elementId: string, thumbPath: string, sourcePath: string, timeout = 1000 * 60 * 2, force: boolean = false) {
|
||||
|
@@ -71,7 +71,6 @@ export class NTQQMsgApi {
|
||||
async queryMsgsWithFilterExWithSeq(peer: Peer, msgSeq: string) {
|
||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||
chatInfo: peer,
|
||||
//searchFields: 3,
|
||||
filterMsgType: [],
|
||||
filterSendersUid: [],
|
||||
filterMsgToTime: '0',
|
||||
@@ -85,7 +84,6 @@ export class NTQQMsgApi {
|
||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||
chatInfo: peer,
|
||||
filterMsgType: [],
|
||||
//searchFields: 3,
|
||||
filterSendersUid: SendersUid,
|
||||
filterMsgToTime: MsgTime,
|
||||
filterMsgFromTime: MsgTime,
|
||||
@@ -102,7 +100,6 @@ export class NTQQMsgApi {
|
||||
filterMsgToTime: '0',
|
||||
filterMsgFromTime: '0',
|
||||
isReverseOrder: false,
|
||||
//searchFields: 3,
|
||||
isIncludeCurrent: true,
|
||||
pageLimit: 1,
|
||||
});
|
||||
@@ -113,7 +110,6 @@ export class NTQQMsgApi {
|
||||
filterMsgType: [],
|
||||
filterSendersUid: [],
|
||||
filterMsgToTime: '0',
|
||||
//searchFields: 3,
|
||||
filterMsgFromTime: '0',
|
||||
isReverseOrder: true,
|
||||
isIncludeCurrent: true,
|
||||
@@ -132,7 +128,6 @@ export class NTQQMsgApi {
|
||||
chatInfo: peer,//此处为Peer 为关键查询参数 没有啥也没有 by mlik iowa
|
||||
filterMsgType: [],
|
||||
filterSendersUid: [],
|
||||
//searchFields: 3,
|
||||
filterMsgToTime: filterMsgToTime,
|
||||
filterMsgFromTime: filterMsgFromTime,
|
||||
isReverseOrder: false,
|
||||
@@ -147,7 +142,6 @@ export class NTQQMsgApi {
|
||||
chatInfo: peer,
|
||||
filterMsgType: [],
|
||||
filterSendersUid: SendersUid,
|
||||
//searchFields: 3,
|
||||
filterMsgToTime: '0',
|
||||
filterMsgFromTime: '0',
|
||||
isReverseOrder: true,
|
||||
|
8
src/core/external/appid.json
vendored
8
src/core/external/appid.json
vendored
@@ -274,13 +274,5 @@
|
||||
"9.9.19-34606": {
|
||||
"appid": 537282307,
|
||||
"qua": "V1_WIN_NQ_9.9.19_34606_GW_B"
|
||||
},
|
||||
"9.9.19-34740": {
|
||||
"appid": 537290691,
|
||||
"qua": "V1_WIN_NQ_9.9.19_34740_GW_B"
|
||||
},
|
||||
"3.2.17-34740": {
|
||||
"appid": 537290727,
|
||||
"qua": "V1_LNX_NQ_3.2.17_34740_GW_B"
|
||||
}
|
||||
}
|
12
src/core/external/offset.json
vendored
12
src/core/external/offset.json
vendored
@@ -350,17 +350,5 @@
|
||||
"3.2.17-34606-arm64": {
|
||||
"send": "7711270",
|
||||
"recv": "7714BA0"
|
||||
},
|
||||
"9.9.19-34740-x64": {
|
||||
"send": "3BDD8D0",
|
||||
"recv": "3BE20D0"
|
||||
},
|
||||
"3.2.17-34740-x64": {
|
||||
"send": "ADDF0A0",
|
||||
"recv": "ADE2AC0"
|
||||
},
|
||||
"3.2.17-34740-arm64": {
|
||||
"send": "7711270",
|
||||
"recv": "7714BA0"
|
||||
}
|
||||
}
|
@@ -3,43 +3,43 @@ import { BuddyCategoryType, FriendRequestNotify } from '@/core/types';
|
||||
export type OnBuddyChangeParams = BuddyCategoryType[];
|
||||
|
||||
export class NodeIKernelBuddyListener {
|
||||
onBuddyListChangedV2(_arg: unknown): any {
|
||||
onBuddyListChangedV2(arg: unknown): any {
|
||||
}
|
||||
|
||||
onAddBuddyNeedVerify(_arg: unknown): any {
|
||||
onAddBuddyNeedVerify(arg: unknown): any {
|
||||
}
|
||||
|
||||
onAddMeSettingChanged(_arg: unknown): any {
|
||||
onAddMeSettingChanged(arg: unknown): any {
|
||||
}
|
||||
|
||||
onAvatarUrlUpdated(_arg: unknown): any {
|
||||
onAvatarUrlUpdated(arg: unknown): any {
|
||||
}
|
||||
|
||||
onBlockChanged(_arg: unknown): any {
|
||||
onBlockChanged(arg: unknown): any {
|
||||
}
|
||||
|
||||
onBuddyDetailInfoChange(_arg: unknown): any {
|
||||
onBuddyDetailInfoChange(arg: unknown): any {
|
||||
}
|
||||
|
||||
onBuddyInfoChange(_arg: unknown): any {
|
||||
onBuddyInfoChange(arg: unknown): any {
|
||||
}
|
||||
|
||||
onBuddyListChange(_arg: OnBuddyChangeParams): any {
|
||||
onBuddyListChange(arg: OnBuddyChangeParams): any {
|
||||
}
|
||||
|
||||
onBuddyRemarkUpdated(_arg: unknown): any {
|
||||
onBuddyRemarkUpdated(arg: unknown): any {
|
||||
}
|
||||
|
||||
onBuddyReqChange(_arg: FriendRequestNotify): any {
|
||||
onBuddyReqChange(arg: FriendRequestNotify): any {
|
||||
}
|
||||
|
||||
onBuddyReqUnreadCntChange(_arg: unknown): any {
|
||||
onBuddyReqUnreadCntChange(arg: unknown): any {
|
||||
}
|
||||
|
||||
onCheckBuddySettingResult(_arg: unknown): any {
|
||||
onCheckBuddySettingResult(arg: unknown): any {
|
||||
}
|
||||
|
||||
onDelBatchBuddyInfos(_arg: unknown): any {
|
||||
onDelBatchBuddyInfos(arg: unknown): any {
|
||||
console.log('onDelBatchBuddyInfos not implemented', ...arguments);
|
||||
}
|
||||
|
||||
@@ -66,12 +66,12 @@ export class NodeIKernelBuddyListener {
|
||||
onDoubtBuddyReqUnreadNumChange(_num: number): void | Promise<void> {
|
||||
}
|
||||
|
||||
onNickUpdated(_arg: unknown): any {
|
||||
onNickUpdated(arg: unknown): any {
|
||||
}
|
||||
|
||||
onSmartInfos(_arg: unknown): any {
|
||||
onSmartInfos(arg: unknown): any {
|
||||
}
|
||||
|
||||
onSpacePermissionInfos(_arg: unknown): any {
|
||||
onSpacePermissionInfos(arg: unknown): any {
|
||||
}
|
||||
}
|
||||
|
@@ -6,14 +6,13 @@ import {
|
||||
PacketMsgFileElement,
|
||||
PacketMsgPicElement,
|
||||
PacketMsgPttElement,
|
||||
PacketMsgReplyElement,
|
||||
PacketMsgVideoElement,
|
||||
PacketMsgVideoElement
|
||||
} from '@/core/packet/message/element';
|
||||
import { ChatType, MsgSourceType, NTMsgType, RawMessage } from '@/core';
|
||||
import { MiniAppRawData, MiniAppReqParams } from '@/core/packet/entities/miniApp';
|
||||
import { AIVoiceChatType } from '@/core/packet/entities/aiChat';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { IndexNode, LongMsgResult, MsgInfo, PushMsgBody } from '@/core/packet/transformer/proto';
|
||||
import { IndexNode, LongMsgResult, MsgInfo } from '@/core/packet/transformer/proto';
|
||||
import { OidbPacket } from '@/core/packet/transformer/base';
|
||||
import { ImageOcrResult } from '@/core/packet/entities/ocrResult';
|
||||
import { gunzipSync } from 'zlib';
|
||||
@@ -77,24 +76,22 @@ export class PacketOperationContext {
|
||||
async UploadResources(msg: PacketMsg[], groupUin: number = 0) {
|
||||
const chatType = groupUin ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C;
|
||||
const peerUid = groupUin ? String(groupUin) : this.context.napcore.basicInfo.uid;
|
||||
const reqList = msg.flatMap((m) =>
|
||||
m.msg
|
||||
.map((e) => {
|
||||
if (e instanceof PacketMsgPicElement) {
|
||||
return this.context.highway.uploadImage({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgVideoElement) {
|
||||
return this.context.highway.uploadVideo({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgPttElement) {
|
||||
return this.context.highway.uploadPtt({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgFileElement) {
|
||||
return this.context.highway.uploadFile({ chatType, peerUid }, e);
|
||||
}
|
||||
return null;
|
||||
})
|
||||
.filter(Boolean)
|
||||
const reqList = msg.flatMap(m =>
|
||||
m.msg.map(e => {
|
||||
if (e instanceof PacketMsgPicElement) {
|
||||
return this.context.highway.uploadImage({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgVideoElement) {
|
||||
return this.context.highway.uploadVideo({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgPttElement) {
|
||||
return this.context.highway.uploadPtt({ chatType, peerUid }, e);
|
||||
} else if (e instanceof PacketMsgFileElement) {
|
||||
return this.context.highway.uploadFile({ chatType, peerUid }, e);
|
||||
}
|
||||
return null;
|
||||
}).filter(Boolean)
|
||||
);
|
||||
const res = await Promise.allSettled(reqList);
|
||||
this.context.logger.info(`上传资源${res.length}个,失败${res.filter((r) => r.status === 'rejected').length}个`);
|
||||
this.context.logger.info(`上传资源${res.length}个,失败${res.filter(r => r.status === 'rejected').length}个`);
|
||||
res.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
this.context.logger.error(`上传第${index + 1}个资源失败:${result.reason.stack}`);
|
||||
@@ -103,13 +100,10 @@ export class PacketOperationContext {
|
||||
}
|
||||
|
||||
async UploadImage(img: PacketMsgPicElement) {
|
||||
await this.context.highway.uploadImage(
|
||||
{
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
peerUid: this.context.napcore.basicInfo.uid,
|
||||
},
|
||||
img
|
||||
);
|
||||
await this.context.highway.uploadImage({
|
||||
chatType: ChatType.KCHATTYPEC2C,
|
||||
peerUid: this.context.napcore.basicInfo.uid
|
||||
}, img);
|
||||
const index = img.msgInfo?.msgInfoBody?.at(0)?.index;
|
||||
if (!index) {
|
||||
throw new Error('img.msgInfo?.msgInfoBody![0].index! is undefined');
|
||||
@@ -124,20 +118,6 @@ export class PacketOperationContext {
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetPttUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadPtt.build(selfUid, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadPtt.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetVideoUrl(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadVideo.build(selfUid, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadVideo.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetGroupImageUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadGroupImage.build(groupUin, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
@@ -145,21 +125,6 @@ export class PacketOperationContext {
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadGroupPtt.build(groupUin, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadImage.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetGroupVideoUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadGroupVideo.build(groupUin, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadImage.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
|
||||
async ImageOCR(imgUrl: string) {
|
||||
const req = trans.ImageOCR.build(imgUrl);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
@@ -172,66 +137,24 @@ export class PacketOperationContext {
|
||||
coordinates: item.polygon.coordinates.map((c) => {
|
||||
return {
|
||||
x: c.x,
|
||||
y: c.y,
|
||||
y: c.y
|
||||
};
|
||||
}),
|
||||
};
|
||||
}),
|
||||
language: res.ocrRspBody.language,
|
||||
language: res.ocrRspBody.language
|
||||
} as ImageOcrResult;
|
||||
}
|
||||
|
||||
private async SendPreprocess(msg: PacketMsg[], groupUin: number = 0) {
|
||||
const ps = msg.map((m) => {
|
||||
return m.msg.map(async (e) => {
|
||||
if (e instanceof PacketMsgReplyElement && !e.targetElems) {
|
||||
this.context.logger.debug(`Cannot find reply element's targetElems, prepare to fetch it...`);
|
||||
if (!e.targetPeer?.peerUid) {
|
||||
this.context.logger.error(`targetPeer is undefined!`);
|
||||
}
|
||||
let targetMsg: NapProtoEncodeStructType<typeof PushMsgBody>[] | undefined;
|
||||
if (e.isGroupReply) {
|
||||
targetMsg = await this.FetchGroupMessage(+(e.targetPeer?.peerUid ?? 0), e.targetMessageSeq, e.targetMessageSeq);
|
||||
} else {
|
||||
targetMsg = await this.FetchC2CMessage(await this.context.napcore.basicInfo.uin2uid(e.targetUin), e.targetMessageSeq, e.targetMessageSeq);
|
||||
}
|
||||
e.targetElems = targetMsg.at(0)?.body?.richText?.elems;
|
||||
e.targetSourceMsg = targetMsg.at(0);
|
||||
}
|
||||
});
|
||||
}).flat();
|
||||
await Promise.all(ps)
|
||||
await this.UploadResources(msg, groupUin);
|
||||
}
|
||||
|
||||
async FetchGroupMessage(groupUin: number, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
|
||||
const req = trans.FetchGroupMessage.build(groupUin, startSeq, endSeq);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.FetchGroupMessage.parse(resp);
|
||||
return res.body.messages
|
||||
}
|
||||
|
||||
async FetchC2CMessage(targetUid: string, startSeq: number, endSeq: number): Promise<NapProtoDecodeStructType<typeof PushMsgBody>[]> {
|
||||
const req = trans.FetchC2CMessage.build(targetUid, startSeq, endSeq);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.FetchC2CMessage.parse(resp);
|
||||
return res.messages
|
||||
}
|
||||
|
||||
async UploadForwardMsg(msg: PacketMsg[], groupUin: number = 0) {
|
||||
await this.SendPreprocess(msg, groupUin);
|
||||
await this.UploadResources(msg, groupUin);
|
||||
const req = trans.UploadForwardMsg.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async MoveGroupFile(
|
||||
groupUin: number,
|
||||
fileUUID: string,
|
||||
currentParentDirectory: string,
|
||||
targetParentDirectory: string
|
||||
) {
|
||||
async MoveGroupFile(groupUin: number, fileUUID: string, currentParentDirectory: string, targetParentDirectory: string) {
|
||||
const req = trans.MoveGroupFile.build(groupUin, fileUUID, currentParentDirectory, targetParentDirectory);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.MoveGroupFile.parse(resp);
|
||||
@@ -251,7 +174,6 @@ export class PacketOperationContext {
|
||||
const res = trans.DownloadGroupFile.parse(resp);
|
||||
return `https://${res.download.downloadDns}/ftn_handler/${Buffer.from(res.download.downloadUrl).toString('hex')}/?fname=`;
|
||||
}
|
||||
|
||||
async GetPrivateFileUrl(self_id: string, fileUUID: string, md5: string) {
|
||||
const req = trans.DownloadPrivateFile.build(self_id, fileUUID, md5);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
@@ -259,6 +181,13 @@ export class PacketOperationContext {
|
||||
return `http://${res.body?.result?.server}:${res.body?.result?.port}${res.body?.result?.url?.slice(8)}&isthumb=0`;
|
||||
}
|
||||
|
||||
async GetGroupPttUrl(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>) {
|
||||
const req = trans.DownloadGroupPtt.build(groupUin, node);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadGroupPtt.parse(resp);
|
||||
return `https://${res.download.info.domain}${res.download.info.urlPath}${res.download.rKeyParam}`;
|
||||
}
|
||||
|
||||
async GetMiniAppAdaptShareInfo(param: MiniAppReqParams) {
|
||||
const req = trans.GetMiniAppAdaptShareInfo.build(param);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
@@ -274,17 +203,12 @@ export class PacketOperationContext {
|
||||
return res.content.map((item) => {
|
||||
return {
|
||||
category: item.category,
|
||||
voices: item.voices,
|
||||
voices: item.voices
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async GetAiVoice(
|
||||
groupUin: number,
|
||||
voiceId: string,
|
||||
text: string,
|
||||
chatType: AIVoiceChatType
|
||||
): Promise<NapProtoDecodeStructType<typeof MsgInfo>> {
|
||||
async GetAiVoice(groupUin: number, voiceId: string, text: string, chatType: AIVoiceChatType): Promise<NapProtoDecodeStructType<typeof MsgInfo>> {
|
||||
let reqTime = 0;
|
||||
const reqMaxTime = 30;
|
||||
const sessionId = crypto.randomBytes(4).readUInt32BE(0);
|
||||
@@ -312,7 +236,6 @@ export class PacketOperationContext {
|
||||
if (!main?.actionData.msgBody) {
|
||||
throw new Error('msgBody is empty');
|
||||
}
|
||||
this.context.logger.debug('rawChains ', inflate.toString('hex'));
|
||||
|
||||
const messagesPromises = main.actionData.msgBody.map(async (msg) => {
|
||||
if (!msg?.body?.richText?.elems) {
|
||||
@@ -328,12 +251,12 @@ export class PacketOperationContext {
|
||||
const groupUin = msg?.responseHead.grp?.groupUin ?? 0;
|
||||
element.picElement = {
|
||||
...element.picElement,
|
||||
originImageUrl: await this.GetGroupImageUrl(groupUin, index!),
|
||||
originImageUrl: await this.GetGroupImageUrl(groupUin, index!)
|
||||
};
|
||||
} else {
|
||||
element.picElement = {
|
||||
...element.picElement,
|
||||
originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index!),
|
||||
originImageUrl: await this.GetImageUrl(this.context.napcore.basicInfo.uid, index!)
|
||||
};
|
||||
}
|
||||
return element;
|
||||
@@ -346,7 +269,7 @@ export class PacketOperationContext {
|
||||
elements: elements,
|
||||
guildId: '',
|
||||
isOnlineMsg: false,
|
||||
msgId: '7467703692092974645', // TODO: no necessary
|
||||
msgId: '7467703692092974645', // TODO: no necessary
|
||||
msgRandom: '0',
|
||||
msgSeq: String(msg.contentHead.sequence ?? 0),
|
||||
msgTime: String(msg.contentHead.timeStamp ?? 0),
|
||||
|
@@ -24,15 +24,12 @@ export class PacketMsgBuilder {
|
||||
}
|
||||
return {
|
||||
responseHead: {
|
||||
fromUin: node.senderUin,
|
||||
type: 0,
|
||||
sigMap: 0,
|
||||
toUin: 0,
|
||||
fromUid: '',
|
||||
fromUin: node.senderUin,
|
||||
toUid: node.groupId ? undefined : selfUid,
|
||||
forward: node.groupId ? undefined : {
|
||||
friendName: node.senderName,
|
||||
},
|
||||
toUid: node.groupId ? undefined : selfUid,
|
||||
grp: node.groupId ? {
|
||||
groupUin: node.groupId,
|
||||
memberName: node.senderName,
|
||||
@@ -43,13 +40,16 @@ export class PacketMsgBuilder {
|
||||
type: node.groupId ? 82 : 9,
|
||||
subType: node.groupId ? undefined : 4,
|
||||
divSeq: node.groupId ? undefined : 4,
|
||||
autoReply: 0,
|
||||
msgId: crypto.randomBytes(4).readUInt32LE(0),
|
||||
sequence: crypto.randomBytes(4).readUInt32LE(0),
|
||||
timeStamp: +node.time.toString().substring(0, 10),
|
||||
field7: BigInt(1),
|
||||
field8: 0,
|
||||
field9: 0,
|
||||
forward: {
|
||||
field1: 0,
|
||||
field2: 0,
|
||||
field3: node.groupId ? 1 : 2,
|
||||
field3: node.groupId ? 0 : 2,
|
||||
unknownBase64: avatar,
|
||||
avatar: avatar
|
||||
}
|
||||
|
@@ -10,7 +10,6 @@ import {
|
||||
MsgInfo,
|
||||
NotOnlineImage,
|
||||
OidbSvcTrpcTcp0XE37_800Response,
|
||||
PushMsgBody,
|
||||
QBigFaceExtra,
|
||||
QSmallFaceExtra,
|
||||
} from '@/core/packet/transformer/proto';
|
||||
@@ -30,8 +29,7 @@ import {
|
||||
SendReplyElement,
|
||||
SendMultiForwardMsgElement,
|
||||
SendTextElement,
|
||||
SendVideoElement,
|
||||
Peer
|
||||
SendVideoElement
|
||||
} from '@/core';
|
||||
import {ForwardMsgBuilder} from '@/common/forward-msg-builder';
|
||||
import {PacketMsg, PacketSendMsgElement} from '@/core/packet/message/message';
|
||||
@@ -148,40 +146,41 @@ export class PacketMsgAtElement extends PacketMsgTextElement {
|
||||
}
|
||||
|
||||
export class PacketMsgReplyElement extends IPacketMsgElement<SendReplyElement> {
|
||||
time: number;
|
||||
targetMessageId: bigint;
|
||||
targetMessageSeq: number;
|
||||
targetMessageClientSeq: number;
|
||||
messageId: bigint;
|
||||
messageSeq: number;
|
||||
messageClientSeq: number;
|
||||
targetUin: number;
|
||||
targetUid: string;
|
||||
targetElems?: NapProtoEncodeStructType<typeof Elem>[];
|
||||
targetSourceMsg?: NapProtoEncodeStructType<typeof PushMsgBody>;
|
||||
targetPeer?: Peer;
|
||||
time: number;
|
||||
elems: PacketMsg[];
|
||||
|
||||
constructor(element: SendReplyElement) {
|
||||
super(element);
|
||||
this.time = +(element.replyElement.replyMsgTime ?? Math.floor(Date.now() / 1000));
|
||||
this.targetMessageId = BigInt(element.replyElement.replayMsgId ?? 0);
|
||||
this.targetMessageSeq = +(element.replyElement.replayMsgSeq ?? 0);
|
||||
this.targetMessageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
|
||||
this.messageId = BigInt(element.replyElement.replayMsgId ?? 0);
|
||||
this.messageSeq = +(element.replyElement.replayMsgSeq ?? 0);
|
||||
this.messageClientSeq = +(element.replyElement.replyMsgClientSeq ?? 0);
|
||||
this.targetUin = +(element.replyElement.senderUin ?? 0);
|
||||
this.targetUid = element.replyElement.senderUidStr ?? '';
|
||||
this.targetPeer = element.replyElement._replyMsgPeer;
|
||||
this.time = +(element.replyElement.replyMsgTime ?? 0);
|
||||
this.elems = []; // TODO: in replyElement.sourceMsgTextElems
|
||||
}
|
||||
|
||||
get isGroupReply(): boolean {
|
||||
return this.targetMessageClientSeq === 0;
|
||||
return this.messageClientSeq === 0;
|
||||
}
|
||||
|
||||
override buildElement(): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
return [{
|
||||
srcMsg: {
|
||||
origSeqs: [this.isGroupReply ? this.targetMessageSeq : this.targetMessageClientSeq],
|
||||
origSeqs: [this.isGroupReply ? this.messageClientSeq : this.messageSeq],
|
||||
senderUin: BigInt(this.targetUin),
|
||||
time: this.time,
|
||||
elems: this.targetElems ?? [],
|
||||
sourceMsg: new NapProtoMsg(PushMsgBody).encode(this.targetSourceMsg ?? {}),
|
||||
toUin: BigInt(0),
|
||||
elems: [], // TODO: in replyElement.sourceMsgTextElems
|
||||
pbReserve: {
|
||||
messageId: this.messageId,
|
||||
},
|
||||
toUin: BigInt(this.targetUin),
|
||||
type: 1,
|
||||
}
|
||||
}];
|
||||
}
|
||||
|
@@ -1,50 +0,0 @@
|
||||
import * as proto from '@/core/packet/transformer/proto';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
||||
|
||||
class DownloadGroupVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
build(groupUin: number, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
||||
reqHead: {
|
||||
common: {
|
||||
requestId: 1,
|
||||
command: 200
|
||||
},
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 2,
|
||||
sceneType: 2,
|
||||
group: {
|
||||
groupUin: groupUin
|
||||
}
|
||||
},
|
||||
client: {
|
||||
agentType: 2,
|
||||
}
|
||||
},
|
||||
download: {
|
||||
node: node,
|
||||
download: {
|
||||
video: {
|
||||
busiType: 0,
|
||||
sceneType: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return OidbBase.build(0x11EA, 200, body, true, false);
|
||||
}
|
||||
|
||||
parse(data: Buffer) {
|
||||
const oidbBody = OidbBase.parse(data).body;
|
||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
||||
}
|
||||
}
|
||||
|
||||
export default new DownloadGroupVideo();
|
@@ -1,51 +0,0 @@
|
||||
import * as proto from '@/core/packet/transformer/proto';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
||||
|
||||
class DownloadPtt extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
build(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
||||
reqHead: {
|
||||
common: {
|
||||
requestId: 1,
|
||||
command: 200
|
||||
},
|
||||
scene: {
|
||||
requestType: 1,
|
||||
businessType: 3,
|
||||
sceneType: 1,
|
||||
c2C: {
|
||||
accountType: 2,
|
||||
targetUid: selfUid
|
||||
},
|
||||
},
|
||||
client: {
|
||||
agentType: 2,
|
||||
}
|
||||
},
|
||||
download: {
|
||||
node: node,
|
||||
download: {
|
||||
video: {
|
||||
busiType: 0,
|
||||
sceneType: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return OidbBase.build(0x126D, 200, body, true, false);
|
||||
}
|
||||
|
||||
parse(data: Buffer) {
|
||||
const oidbBody = OidbBase.parse(data).body;
|
||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
||||
}
|
||||
}
|
||||
|
||||
export default new DownloadPtt();
|
@@ -1,51 +0,0 @@
|
||||
import * as proto from '@/core/packet/transformer/proto';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { OidbPacket, PacketTransformer } from '@/core/packet/transformer/base';
|
||||
import OidbBase from '@/core/packet/transformer/oidb/oidbBase';
|
||||
import { IndexNode } from '@/core/packet/transformer/proto';
|
||||
|
||||
class DownloadVideo extends PacketTransformer<typeof proto.NTV2RichMediaResp> {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
build(selfUid: string, node: NapProtoEncodeStructType<typeof IndexNode>): OidbPacket {
|
||||
const body = new NapProtoMsg(proto.NTV2RichMediaReq).encode({
|
||||
reqHead: {
|
||||
common: {
|
||||
requestId: 1,
|
||||
command: 200
|
||||
},
|
||||
scene: {
|
||||
requestType: 2,
|
||||
businessType: 2,
|
||||
sceneType: 1,
|
||||
c2C: {
|
||||
accountType: 2,
|
||||
targetUid: selfUid
|
||||
},
|
||||
},
|
||||
client: {
|
||||
agentType: 2,
|
||||
}
|
||||
},
|
||||
download: {
|
||||
node: node,
|
||||
download: {
|
||||
video: {
|
||||
busiType: 0,
|
||||
sceneType: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return OidbBase.build(0x11E9, 200, body, true, false);
|
||||
}
|
||||
|
||||
parse(data: Buffer) {
|
||||
const oidbBody = OidbBase.parse(data).body;
|
||||
return new NapProtoMsg(proto.NTV2RichMediaResp).decode(oidbBody);
|
||||
}
|
||||
}
|
||||
|
||||
export default new DownloadVideo();
|
@@ -13,6 +13,3 @@ export { default as UploadPrivatePtt } from './UploadPrivatePtt';
|
||||
export { default as UploadPrivateVideo } from './UploadPrivateVideo';
|
||||
export { default as DownloadImage } from './DownloadImage';
|
||||
export { default as DownloadGroupImage } from './DownloadGroupImage';
|
||||
export { default as DownloadVideo } from './DownloadVideo';
|
||||
export { default as DownloadGroupVideo } from './DownloadGroupVideo';
|
||||
export { default as DownloadPtt } from './DownloadPtt';
|
@@ -1,27 +0,0 @@
|
||||
import * as proto from '@/core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { OidbPacket, PacketHexStrBuilder, PacketTransformer } from '@/core/packet/transformer/base';
|
||||
|
||||
class FetchC2CMessage extends PacketTransformer<typeof proto.SsoGetC2cMsgResponse> {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
build(targetUid: string, startSeq: number, endSeq: number): OidbPacket {
|
||||
const req = new NapProtoMsg(proto.SsoGetC2cMsg).encode({
|
||||
friendUid: targetUid,
|
||||
startSequence: startSeq,
|
||||
endSequence: endSeq,
|
||||
});
|
||||
return {
|
||||
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg',
|
||||
data: PacketHexStrBuilder(req)
|
||||
};
|
||||
}
|
||||
|
||||
parse(data: Buffer) {
|
||||
return new NapProtoMsg(proto.SsoGetC2cMsgResponse).decode(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new FetchC2CMessage();
|
@@ -1,30 +0,0 @@
|
||||
import * as proto from '@/core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from '@napneko/nap-proto-core';
|
||||
import { OidbPacket, PacketHexStrBuilder, PacketTransformer } from '@/core/packet/transformer/base';
|
||||
|
||||
class FetchGroupMessage extends PacketTransformer<typeof proto.SsoGetGroupMsgResponse> {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
build(groupUin: number, startSeq: number, endSeq: number): OidbPacket {
|
||||
const req = new NapProtoMsg(proto.SsoGetGroupMsg).encode({
|
||||
info: {
|
||||
groupUin: groupUin,
|
||||
startSequence: startSeq,
|
||||
endSequence: endSeq
|
||||
},
|
||||
direction: true
|
||||
});
|
||||
return {
|
||||
cmd: 'trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg',
|
||||
data: PacketHexStrBuilder(req)
|
||||
};
|
||||
}
|
||||
|
||||
parse(data: Buffer) {
|
||||
return new NapProtoMsg(proto.SsoGetGroupMsgResponse).decode(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new FetchGroupMessage();
|
@@ -1,4 +1,2 @@
|
||||
export { default as UploadForwardMsg } from './UploadForwardMsg';
|
||||
export { default as FetchGroupMessage } from './FetchGroupMessage';
|
||||
export { default as FetchC2CMessage } from './FetchC2CMessage';
|
||||
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
||||
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
@@ -13,15 +13,13 @@ import {
|
||||
export const ContentHead = {
|
||||
type: ProtoField(1, ScalarType.UINT32),
|
||||
subType: ProtoField(2, ScalarType.UINT32, true),
|
||||
c2cCmd: ProtoField(3, ScalarType.UINT32, true),
|
||||
ranDom: ProtoField(4, ScalarType.UINT32, true),
|
||||
divSeq: ProtoField(3, ScalarType.UINT32, true),
|
||||
msgId: ProtoField(4, ScalarType.UINT32, true),
|
||||
sequence: ProtoField(5, ScalarType.UINT32, true),
|
||||
timeStamp: ProtoField(6, ScalarType.UINT32, true),
|
||||
pkgNum: ProtoField(7, ScalarType.UINT64, true),
|
||||
pkgIndex: ProtoField(8, ScalarType.UINT32, true),
|
||||
divSeq: ProtoField(9, ScalarType.UINT32, true),
|
||||
autoReply: ProtoField(10, ScalarType.UINT32),
|
||||
ntMsgSeq: ProtoField(10, ScalarType.UINT32, true),
|
||||
field7: ProtoField(7, ScalarType.UINT64, true),
|
||||
field8: ProtoField(8, ScalarType.UINT32, true),
|
||||
field9: ProtoField(9, ScalarType.UINT32, true),
|
||||
newId: ProtoField(12, ScalarType.UINT64, true),
|
||||
forward: ProtoField(15, () => ForwardHead, true),
|
||||
};
|
||||
|
@@ -1,6 +0,0 @@
|
||||
import { ProtoField, ScalarType } from '@napneko/nap-proto-core';
|
||||
|
||||
export const FileId = {
|
||||
appid: ProtoField(4, ScalarType.UINT32, true),
|
||||
ttl: ProtoField(10, ScalarType.UINT32, true),
|
||||
};
|
@@ -249,7 +249,7 @@ export interface NodeIKernelGroupService {
|
||||
|
||||
reqToJoinGroup(groupCode: string, arg: unknown): void;
|
||||
|
||||
setGroupShutUp(groupCode: string, shutUp: boolean): Promise<GeneralCallResult>;
|
||||
setGroupShutUp(groupCode: string, shutUp: boolean): void;
|
||||
|
||||
getGroupShutUpMemberList(groupCode: string): Promise<GeneralCallResult>;
|
||||
|
||||
|
@@ -148,11 +148,10 @@ export interface NodeIKernelMsgService {
|
||||
msgList: RawMessage[]
|
||||
}>;
|
||||
|
||||
// getMsgService/getMsgs { chatType: 2, peerUid: '975206796', privilegeFlag: 336068800 } 0 20 true
|
||||
getMsgs(peer: Peer & { privilegeFlag: number }, msgId: string, count: number, queryOrder: boolean): Promise<GeneralCallResult & {
|
||||
msgList: RawMessage[]
|
||||
}>;
|
||||
//@deprecated
|
||||
getMsgs(peer: Peer, msgId: string, count: unknown, queryOrder: boolean): Promise<unknown>;
|
||||
|
||||
//@deprecated
|
||||
getMsgsIncludeSelf(peer: Peer, msgId: string, count: number, queryOrder: boolean): Promise<GeneralCallResult & {
|
||||
msgList: RawMessage[]
|
||||
}>;
|
||||
|
@@ -1,15 +1,4 @@
|
||||
import {
|
||||
ElementType,
|
||||
MessageElement,
|
||||
NTGrayTipElementSubTypeV2,
|
||||
PicSubType,
|
||||
PicType,
|
||||
TipAioOpGrayTipElement,
|
||||
TipGroupElement,
|
||||
NTVideoType,
|
||||
FaceType,
|
||||
Peer
|
||||
} from './msg';
|
||||
import { ElementType, MessageElement, NTGrayTipElementSubTypeV2, PicSubType, PicType, TipAioOpGrayTipElement, TipGroupElement, NTVideoType, FaceType } from './msg';
|
||||
|
||||
type ElementFullBase = Omit<MessageElement, 'elementType' | 'elementId' | 'extBufForUI'>;
|
||||
|
||||
@@ -224,9 +213,6 @@ export interface ReplyElement {
|
||||
senderUidStr?: string;
|
||||
replyMsgTime?: string;
|
||||
replyMsgClientSeq?: string;
|
||||
// HACK: Attributes that were not originally available,
|
||||
// but were added due to NTQQ and NapCat's internal implementation, are used to supplement NapCat
|
||||
_replyMsgPeer?: Peer;
|
||||
}
|
||||
|
||||
export interface CalendarElement {
|
||||
|
@@ -403,7 +403,7 @@ export interface NTGroupGrayMember {
|
||||
}
|
||||
/**
|
||||
* 群灰色提示邀请者和被邀请者接口
|
||||
*
|
||||
*
|
||||
* */
|
||||
export interface NTGroupGrayInviterAndInvite {
|
||||
invited: NTGroupGrayMember;
|
||||
@@ -501,15 +501,13 @@ export interface RawMessage {
|
||||
elements: MessageElement[];// 消息元素
|
||||
sourceType: MsgSourceType;// 消息来源类型
|
||||
isOnlineMsg: boolean;// 是否为在线消息
|
||||
clientSeq?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询消息参数接口
|
||||
*/
|
||||
export interface QueryMsgsParams {
|
||||
chatInfo: Peer & { privilegeFlag?: number };
|
||||
//searchFields: number;
|
||||
chatInfo: Peer;
|
||||
filterMsgType: Array<{ type: NTMsgType, subType: Array<number> }>;
|
||||
filterSendersUid: string[];
|
||||
filterMsgFromTime: string;
|
||||
@@ -567,4 +565,4 @@ export enum FaceType {
|
||||
AniSticke = 3, // 动画贴纸
|
||||
Lottie = 4,// 新格式表情
|
||||
Poke = 5 // 可变Poke
|
||||
}
|
||||
}
|
@@ -132,26 +132,18 @@ export enum BuddyReqType {
|
||||
KMEINITIATORWAITPEERCONFIRM = 13
|
||||
}
|
||||
|
||||
// 其中 ? 代表新版本参数
|
||||
export interface FriendRequest {
|
||||
isBuddy?: boolean;
|
||||
isInitiator?: boolean;
|
||||
isDecide: boolean;
|
||||
friendUid: string;
|
||||
reqType: BuddyReqType,
|
||||
reqTime: string; // 时间戳 秒
|
||||
flag?: number; // 0
|
||||
preGroupingId?: number; // 0
|
||||
commFriendNum?: number; // 共同好友数
|
||||
extWords: string; // 申请人填写的验证消息
|
||||
isUnread: boolean;
|
||||
isDoubt?: boolean; // 是否是可疑的好友请求
|
||||
nameMore?: string;
|
||||
friendNick: string;
|
||||
sourceId: number;
|
||||
groupCode: string;
|
||||
isBuddy?: boolean;
|
||||
isAgreed?: boolean;
|
||||
relation?: number;
|
||||
groupCode: string
|
||||
}
|
||||
|
||||
export interface FriendRequestNotify {
|
||||
|
@@ -15,10 +15,7 @@ export default class SetGroupWholeBan extends OneBotAction<Payload, null> {
|
||||
|
||||
async _handle(payload: Payload): Promise<null> {
|
||||
const enable = payload.enable?.toString() !== 'false';
|
||||
let res = await this.core.apis.GroupApi.banGroup(payload.group_id.toString(), enable);
|
||||
if (res.result !== 0) {
|
||||
throw new Error(`SetGroupWholeBan failed: ${res.errMsg} ${res.result}`);
|
||||
}
|
||||
await this.core.apis.GroupApi.banGroup(payload.group_id.toString(), enable);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@@ -174,11 +174,9 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
||||
nickname: string,
|
||||
}, dp: number = 0): Promise<{
|
||||
finallySendElements: SendArkElement,
|
||||
res_id?: string,
|
||||
deleteAfterSentFiles: string[],
|
||||
res_id?: string
|
||||
} | null> {
|
||||
const packetMsg: PacketMsg[] = [];
|
||||
let delFiles: string[] = [];
|
||||
for (const node of messageNodes) {
|
||||
if (dp >= 3) {
|
||||
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
|
||||
@@ -194,11 +192,9 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
||||
nickname: (node.data.nickname || node.data.name) ?? parentMeta?.nickname ?? 'QQ用户',
|
||||
}, dp + 1);
|
||||
sendElements = uploadReturnData?.finallySendElements ? [uploadReturnData.finallySendElements] : [];
|
||||
delFiles.push(...(uploadReturnData?.deleteAfterSentFiles || []));
|
||||
} else {
|
||||
const sendElementsCreateReturn = await this.obContext.apis.MsgApi.createSendElements(OB11Data, msgPeer);
|
||||
sendElements = sendElementsCreateReturn.sendElements;
|
||||
delFiles.push(...sendElementsCreateReturn.deleteAfterSentFiles);
|
||||
}
|
||||
|
||||
const packetMsgElements: rawMsgWithSendMsg = {
|
||||
@@ -222,8 +218,7 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
||||
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(nodeMsg.Peer, [nodeMsg.MsgId])).msgList[0];
|
||||
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 开始转换 ${stringifyWithBigInt(msg)}`);
|
||||
if (msg) {
|
||||
let msgCache = await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
|
||||
delFiles.push(...msgCache);
|
||||
await this.core.apis.FileApi.downloadRawMsgMedia([msg]);
|
||||
const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgToPacketMsg(msg, msgPeer);
|
||||
this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`);
|
||||
packetMsg.push(transformedMsg);
|
||||
@@ -239,7 +234,6 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
||||
const resid = await this.core.apis.PacketApi.pkt.operation.UploadForwardMsg(packetMsg, msgPeer.chatType === ChatType.KCHATTYPEGROUP ? +msgPeer.peerUid : 0);
|
||||
const forwardJson = ForwardMsgBuilder.fromPacketMsg(resid, packetMsg, source, news, summary, prompt);
|
||||
return {
|
||||
deleteAfterSentFiles: delFiles,
|
||||
finallySendElements: {
|
||||
elementType: ElementType.ARK,
|
||||
elementId: '',
|
||||
@@ -261,7 +255,7 @@ export class SendMsgBase extends OneBotAction<OB11PostSendMsg, ReturnDataType> {
|
||||
const res_id = uploadReturnData?.res_id;
|
||||
const finallySendElements = uploadReturnData?.finallySendElements;
|
||||
if (!finallySendElements) throw Error('转发消息失败,生成节点为空');
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(msgPeer, [finallySendElements], uploadReturnData.deleteAfterSentFiles || []).catch(() => undefined);
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(msgPeer, [finallySendElements], []).catch(() => undefined);
|
||||
return { message: returnMsg ?? null, res_id: res_id! };
|
||||
}
|
||||
|
||||
|
@@ -100,7 +100,7 @@ export class OneBotMsgApi {
|
||||
let qq: string = 'all';
|
||||
if (element.atType !== NTMsgAtType.ATTYPEALL) {
|
||||
const { atNtUid, atUid } = element;
|
||||
qq = !atUid || atUid === '0' ? await this.core.apis.UserApi.getUinByUidV2(atNtUid) : String(Number(atUid) >>> 0);
|
||||
qq = !atUid || atUid === '0' ? await this.core.apis.UserApi.getUinByUidV2(atNtUid) : atUid;
|
||||
}
|
||||
return {
|
||||
type: OB11MessageDataType.at,
|
||||
@@ -150,31 +150,12 @@ export class OneBotMsgApi {
|
||||
};
|
||||
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileUuid);
|
||||
FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
||||
if (this.core.apis.PacketApi.available) {
|
||||
let url;
|
||||
try {
|
||||
url = await this.core.apis.FileApi.getFileUrl(msg.chatType, msg.peerUid, element.fileUuid, element.file10MMd5)
|
||||
} catch (error) {
|
||||
url = '';
|
||||
}
|
||||
if (url) {
|
||||
return {
|
||||
type: OB11MessageDataType.file,
|
||||
data: {
|
||||
file: element.fileName,
|
||||
file_id: element.fileUuid,
|
||||
file_size: element.fileSize,
|
||||
url: url,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: OB11MessageDataType.file,
|
||||
data: {
|
||||
file: element.fileName,
|
||||
file_id: element.fileUuid,
|
||||
file_size: element.fileSize
|
||||
file_size: element.fileSize,
|
||||
},
|
||||
};
|
||||
},
|
||||
@@ -244,13 +225,17 @@ export class OneBotMsgApi {
|
||||
},
|
||||
|
||||
replyElement: async (element, msg) => {
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords);
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
guildId: '',
|
||||
};
|
||||
if (!records || !element.replyMsgTime || !element.senderUidStr) {
|
||||
this.core.context.logger.logError('似乎是旧版客户端,获取不到引用的消息', element.replayMsgSeq);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 创建回复数据的通用方法
|
||||
const createReplyData = (msgId: string): OB11MessageData => ({
|
||||
type: OB11MessageDataType.reply,
|
||||
data: {
|
||||
@@ -258,96 +243,48 @@ export class OneBotMsgApi {
|
||||
},
|
||||
});
|
||||
|
||||
// 查找记录
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords);
|
||||
|
||||
// 特定账号的特殊处理
|
||||
if (records && (records.peerUin === '284840486' || records.peerUin === '1094950020')) {
|
||||
if (records.peerUin === '284840486' || records.peerUin === '1094950020') {
|
||||
return createReplyData(records.msgId);
|
||||
}
|
||||
let replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(peer, element.replayMsgSeq, records.msgTime, [element.senderUidStr])).msgList;
|
||||
let replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||
|
||||
// 获取消息的通用方法组
|
||||
const tryFetchMethods = async (msgSeq: string, senderUid?: string, msgTime?: string, msgRandom?: string): Promise<RawMessage | undefined> => {
|
||||
try {
|
||||
// 方法1:通过序号和时间筛选
|
||||
if (senderUid && msgTime) {
|
||||
const replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV2(
|
||||
peer, msgSeq, msgTime, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
this.core.context.logger.logWarn(`方法1查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
||||
}
|
||||
|
||||
// 方法2:直接通过序号获取
|
||||
const replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(
|
||||
peer, msgSeq, 1, true, true
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
this.core.context.logger.logWarn(`方法2查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
||||
|
||||
// 方法3:另一种筛选方式
|
||||
if (senderUid) {
|
||||
const replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV3(
|
||||
peer, msgSeq, [senderUid]
|
||||
)).msgList;
|
||||
|
||||
const replyMsg = msgRandom
|
||||
? replyMsgList.find(msg => msg.msgRandom === msgRandom)
|
||||
: replyMsgList.find(msg => msg.msgSeq === msgSeq);
|
||||
|
||||
if (replyMsg) return replyMsg;
|
||||
|
||||
this.core.context.logger.logWarn(`方法3查询失败,序号: ${msgSeq}, 消息数: ${replyMsgList.length}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} catch (error) {
|
||||
this.core.context.logger.logError('查询回复消息出错', error);
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// 有记录情况下,使用完整信息查询
|
||||
if (records && element.replyMsgTime && element.senderUidStr) {
|
||||
const replyMsg = await tryFetchMethods(
|
||||
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||
this.core.context.logger.logError(
|
||||
'筛选结果,筛选消息失败,将使用Fallback-1 Seq: ',
|
||||
element.replayMsgSeq,
|
||||
element.senderUidStr,
|
||||
records.msgTime,
|
||||
records.msgRandom
|
||||
',消息长度:',
|
||||
replyMsgList.length
|
||||
);
|
||||
|
||||
if (replyMsg) {
|
||||
return createReplyData(replyMsg.msgId);
|
||||
}
|
||||
|
||||
this.core.context.logger.logError('所有查找方法均失败,获取不到带记录的引用消息', element.replayMsgSeq);
|
||||
} else {
|
||||
// 旧版客户端或不完整记录的情况,也尝试使用相同流程
|
||||
this.core.context.logger.logWarn('似乎是旧版客户端,尝试仅通过序号获取引用消息', element.replayMsgSeq);
|
||||
|
||||
const replyMsg = await tryFetchMethods(element.replayMsgSeq);
|
||||
|
||||
if (replyMsg) {
|
||||
return createReplyData(replyMsg.msgId);
|
||||
}
|
||||
|
||||
this.core.context.logger.logError('所有查找方法均失败,获取不到旧客户端的引用消息', element.replayMsgSeq);
|
||||
replyMsgList = (await this.core.apis.MsgApi.getMsgsBySeqAndCount(peer, element.replayMsgSeq, 1, true, true)).msgList;
|
||||
replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||
}
|
||||
|
||||
return null;
|
||||
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||
this.core.context.logger.logWarn(
|
||||
'筛选消息失败,将使用Fallback-2 Seq:',
|
||||
element.replayMsgSeq,
|
||||
',消息长度:',
|
||||
replyMsgList.length
|
||||
);
|
||||
replyMsgList = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeqV3(peer, element.replayMsgSeq, [element.senderUidStr])).msgList;
|
||||
replyMsg = replyMsgList.find(msg => msg.msgRandom === records.msgRandom);
|
||||
}
|
||||
|
||||
|
||||
// 丢弃该消息段
|
||||
if (!replyMsg || records.msgRandom !== replyMsg.msgRandom) {
|
||||
this.core.context.logger.logError(
|
||||
'最终筛选结果,筛选消息失败,获取不到引用的消息 Seq: ',
|
||||
element.replayMsgSeq,
|
||||
',消息长度:',
|
||||
replyMsgList.length
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return createReplyData(replyMsg.msgId);
|
||||
},
|
||||
|
||||
videoElement: async (element, msg, elementWrapper) => {
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
@@ -394,17 +331,7 @@ export class OneBotMsgApi {
|
||||
|
||||
//开始兜底
|
||||
if (!videoDownUrl) {
|
||||
if (this.core.apis.PacketApi.available) {
|
||||
try {
|
||||
videoDownUrl = await this.core.apis.FileApi.getVideoUrlPacket(msg.peerUid, element.fileUuid);
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('获取视频url失败', (e as Error).stack);
|
||||
videoDownUrl = element.filePath;
|
||||
}
|
||||
} else {
|
||||
videoDownUrl = element.filePath;
|
||||
}
|
||||
|
||||
videoDownUrl = element.filePath;
|
||||
}
|
||||
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, element.fileUuid, element.fileName);
|
||||
return {
|
||||
@@ -424,28 +351,6 @@ export class OneBotMsgApi {
|
||||
guildId: '',
|
||||
};
|
||||
const fileCode = FileNapCatOneBotUUID.encode(peer, msg.msgId, elementWrapper.elementId, '', element.fileName);
|
||||
let pttUrl = '';
|
||||
if (this.core.apis.PacketApi.available) {
|
||||
try {
|
||||
pttUrl = await this.core.apis.FileApi.getPttUrl(msg.peerUid, element.fileUuid);
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('获取语音url失败', (e as Error).stack);
|
||||
pttUrl = element.filePath;
|
||||
}
|
||||
} else {
|
||||
pttUrl = element.filePath;
|
||||
}
|
||||
if (pttUrl) {
|
||||
return {
|
||||
type: OB11MessageDataType.voice,
|
||||
data: {
|
||||
file: fileCode,
|
||||
path: element.filePath,
|
||||
url: pttUrl,
|
||||
file_size: element.fileSize,
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
type: OB11MessageDataType.voice,
|
||||
data: {
|
||||
@@ -562,8 +467,6 @@ export class OneBotMsgApi {
|
||||
replayMsgId: replyMsg.msgId, // raw.msgId
|
||||
senderUin: replyMsg.senderUin,
|
||||
senderUinStr: replyMsg.senderUin,
|
||||
replyMsgClientSeq: replyMsg.clientSeq,
|
||||
_replyMsgPeer: replyMsgM.Peer
|
||||
},
|
||||
} :
|
||||
undefined;
|
||||
|
@@ -50,6 +50,7 @@ import {
|
||||
import { OB11Message } from './types';
|
||||
import { IOB11NetworkAdapter } from '@/onebot/network/adapter';
|
||||
import { OB11HttpSSEServerAdapter } from './network/http-server-sse';
|
||||
import { OB11PluginAdapter } from './network/plugin';
|
||||
|
||||
//OneBot实现类
|
||||
export class NapCatOneBot11Adapter {
|
||||
@@ -113,9 +114,9 @@ export class NapCatOneBot11Adapter {
|
||||
//创建NetWork服务
|
||||
|
||||
// 注册Plugin 如果需要基于NapCat进行快速开发
|
||||
// this.networkManager.registerAdapter(
|
||||
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
||||
// );
|
||||
this.networkManager.registerAdapter(
|
||||
new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
||||
);
|
||||
for (const key of ob11Config.network.httpServers) {
|
||||
if (key.enable) {
|
||||
this.networkManager.registerAdapter(
|
||||
@@ -334,7 +335,7 @@ export class NapCatOneBot11Adapter {
|
||||
for (let i = 0; i < reqs.unreadNums; i++) {
|
||||
const req = reqs.buddyReqs[i];
|
||||
if (!req) continue;
|
||||
if (!!req.isInitiator || (req.isDecide && req.reqType !== BuddyReqType.KMEINITIATORWAITPEERCONFIRM) || !req.isUnread) {
|
||||
if (!!req.isInitiator || (req.isDecide && req.reqType !== BuddyReqType.KMEINITIATORWAITPEERCONFIRM)) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -352,6 +353,7 @@ export class NapCatOneBot11Adapter {
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this.context.session
|
||||
.getBuddyService()
|
||||
.addKernelBuddyListener(proxiedListenerOf(buddyListener, this.context.logger));
|
||||
|
@@ -22,7 +22,7 @@ export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
|
||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
if (event.post_type === 'message') {
|
||||
plugin_onmessage(this.config.name, this.core, this.obContext, event as OB11Message, this.actions, this).then().catch();
|
||||
plugin_onmessage(this.config.name, this.core, this.obContext, event as OB11Message, this.actions, this).then().catch(console.log);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -39,11 +39,8 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
||||
wsClient.close();
|
||||
return;
|
||||
}
|
||||
// 鉴权 close 不会立刻销毁 当前返回可避免挂载message事件 close 并未立刻关闭 而是存在timer操作后关闭
|
||||
// 引发高危漏洞
|
||||
if (!this.authorize(this.config.token, wsClient, wsReq)) {
|
||||
return;
|
||||
}
|
||||
//鉴权
|
||||
this.authorize(this.config.token, wsClient, wsReq);
|
||||
const paramUrl = wsReq.url?.indexOf('?') !== -1 ? wsReq.url?.substring(0, wsReq.url?.indexOf('?')) : wsReq.url;
|
||||
const isApiConnect = paramUrl === '/api' || paramUrl === '/api/';
|
||||
if (!isApiConnect) {
|
||||
@@ -148,16 +145,15 @@ export class OB11WebSocketServerAdapter extends IOB11NetworkAdapter<WebsocketSer
|
||||
}
|
||||
|
||||
private authorize(token: string | undefined, wsClient: WebSocket, wsReq: IncomingMessage) {
|
||||
if (!token || token.length == 0) return true;//客户端未设置密钥
|
||||
if (!token || token.length == 0) return;//客户端未设置密钥
|
||||
const QueryClientToken = urlParse.parse(wsReq?.url || '', true).query['access_token'];
|
||||
const HeaderClientToken = wsReq.headers.authorization?.split('Bearer ').pop() || '';
|
||||
const ClientToken = typeof (QueryClientToken) === 'string' && QueryClientToken !== '' ? QueryClientToken : HeaderClientToken;
|
||||
if (ClientToken === token) {
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
wsClient.send(JSON.stringify(OB11Response.res(null, 'failed', 1403, 'token验证失败')));
|
||||
wsClient.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
private checkStateAndReply<T>(data: T, wsClient: WebSocket) {
|
||||
|
203
src/plugin/TapAccountManager.ts
Normal file
203
src/plugin/TapAccountManager.ts
Normal file
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* TapTap账号管理类
|
||||
*/
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
export class TapAccountManager {
|
||||
private userBindTapMap = new Map<string, {
|
||||
default: string;
|
||||
list: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
}>;
|
||||
}>();
|
||||
private dataFilePath: string;
|
||||
|
||||
constructor(dataDir: string = './data') {
|
||||
// 确保数据目录存在
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
this.dataFilePath = path.join(dataDir, 'tap_accounts.json');
|
||||
this.loadData();
|
||||
}
|
||||
|
||||
saveData() {
|
||||
try {
|
||||
// 将 Map 转换为可序列化的对象
|
||||
const dataObj: Record<string, any> = {};
|
||||
this.userBindTapMap.forEach((value, key) => {
|
||||
dataObj[key] = value;
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
this.dataFilePath,
|
||||
JSON.stringify(dataObj, null, 2),
|
||||
'utf-8'
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('保存 TapTap 账号数据失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
loadData() {
|
||||
try {
|
||||
if (fs.existsSync(this.dataFilePath)) {
|
||||
const fileContent = fs.readFileSync(this.dataFilePath, 'utf-8');
|
||||
const dataObj = JSON.parse(fileContent);
|
||||
|
||||
// 清空当前数据并加载新数据
|
||||
this.userBindTapMap.clear();
|
||||
for (const [key, value] of Object.entries(dataObj)) {
|
||||
this.userBindTapMap.set(key, value as any);
|
||||
}
|
||||
|
||||
console.log('TapTap 账号数据已加载');
|
||||
} else {
|
||||
console.log('未找到 TapTap 账号数据文件,将创建新的数据存储');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载 TapTap 账号数据失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定TapTap ID
|
||||
*/
|
||||
async bindAccount(userId: string, tapId: string, characterName: string): Promise<boolean> {
|
||||
// 用户首次绑定账号
|
||||
if (!this.userBindTapMap.has(userId)) {
|
||||
this.userBindTapMap.set(userId, {
|
||||
default: tapId,
|
||||
list: [{
|
||||
id: tapId,
|
||||
name: characterName
|
||||
}]
|
||||
});
|
||||
await this.saveData();
|
||||
return true;
|
||||
}
|
||||
|
||||
// 用户已有账号,追加新账号
|
||||
const userData = this.userBindTapMap.get(userId)!;
|
||||
// 检查是否已经绑定过该ID
|
||||
if (!userData.list.some(item => item.id === tapId)) {
|
||||
userData.list.push({
|
||||
id: tapId,
|
||||
name: characterName
|
||||
});
|
||||
userData.default = tapId; // 新绑定的账号自动设为默认
|
||||
await this.saveData();
|
||||
return true;
|
||||
}
|
||||
|
||||
// 账号已存在
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换默认TapTap ID
|
||||
*/
|
||||
async switchAccount(userId: string, tapId: string): Promise<boolean> {
|
||||
const userData = this.userBindTapMap.get(userId);
|
||||
if (!userData) return false;
|
||||
|
||||
const accountItem = userData.list.find(item => item.id === tapId);
|
||||
if (!accountItem) return false;
|
||||
|
||||
userData.default = tapId;
|
||||
await this.saveData();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除绑定的TapTap ID
|
||||
* @returns 删除结果、剩余默认账号信息(如果有)
|
||||
*/
|
||||
async deleteAccount(userId: string, tapId: string): Promise<{
|
||||
success: boolean;
|
||||
deletedAccount?: { id: string; name: string; };
|
||||
defaultAccount?: { id: string; name: string; };
|
||||
isEmpty: boolean;
|
||||
}> {
|
||||
const userData = this.userBindTapMap.get(userId);
|
||||
if (!userData) {
|
||||
return { success: false, isEmpty: true };
|
||||
}
|
||||
|
||||
const index = userData.list.findIndex(item => item.id === tapId);
|
||||
if (index === -1) {
|
||||
return { success: false, isEmpty: false };
|
||||
}
|
||||
|
||||
const deletedAccount = userData.list[index];
|
||||
userData.list.splice(index, 1);
|
||||
|
||||
// 如果删除的是当前默认账号,则需要重新设置默认账号
|
||||
if (userData.default === tapId) {
|
||||
userData.default = userData.list.length > 0 ? userData.list[0]?.id ?? '' : '';
|
||||
}
|
||||
|
||||
// 如果没有绑定账号了,则删除该用户的记录
|
||||
let result;
|
||||
if (userData.list.length === 0) {
|
||||
this.userBindTapMap.delete(userId);
|
||||
result = {
|
||||
success: true,
|
||||
deletedAccount,
|
||||
isEmpty: true
|
||||
};
|
||||
} else {
|
||||
const defaultAccount = userData.list.find(item => item.id === userData.default);
|
||||
result = {
|
||||
success: true,
|
||||
deletedAccount,
|
||||
defaultAccount,
|
||||
isEmpty: false
|
||||
};
|
||||
}
|
||||
|
||||
await this.saveData();
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户账号列表
|
||||
*/
|
||||
getAccountList(userId: string): {
|
||||
hasAccounts: boolean;
|
||||
accounts?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
isDefault: boolean;
|
||||
}>;
|
||||
} {
|
||||
const userData = this.userBindTapMap.get(userId);
|
||||
if (!userData || userData.list.length === 0) {
|
||||
return { hasAccounts: false };
|
||||
}
|
||||
|
||||
const accounts = userData.list.map(item => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
isDefault: item.id === userData.default
|
||||
}));
|
||||
|
||||
return { hasAccounts: true, accounts };
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取用户当前默认账号ID
|
||||
*/
|
||||
getDefaultAccount(userId: string): {
|
||||
hasDefault: boolean;
|
||||
tapId?: string;
|
||||
} {
|
||||
const userData = this.userBindTapMap.get(userId);
|
||||
if (!userData || !userData.default) {
|
||||
return { hasDefault: false };
|
||||
}
|
||||
return { hasDefault: true, tapId: userData.default };
|
||||
}
|
||||
}
|
255
src/plugin/api.ts
Normal file
255
src/plugin/api.ts
Normal file
@@ -0,0 +1,255 @@
|
||||
export interface GameUserDetail {
|
||||
data: Data;
|
||||
now: number;
|
||||
success: boolean;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Data {
|
||||
config: Config;
|
||||
external_url: string;
|
||||
is_bind: boolean;
|
||||
list: DataList[];
|
||||
next_page: string;
|
||||
prev_page: string;
|
||||
role_id: string;
|
||||
sharing: Sharing;
|
||||
show_bind_button: boolean;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
app_icon: AppIcon;
|
||||
banner: Banner;
|
||||
font_class: string;
|
||||
font_color: string;
|
||||
label: Label;
|
||||
show_bind_expired_alert: boolean;
|
||||
tint: number;
|
||||
title: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface AppIcon {
|
||||
color: string;
|
||||
height: number;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_size: number;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
width: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Banner {
|
||||
color: string;
|
||||
height: number;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_size: number;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
width: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Label {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface DataList {
|
||||
basic_module?: BasicModule;
|
||||
character_module?: CharacterModule;
|
||||
episode_module?: EpisodeModule;
|
||||
is_sharing: boolean;
|
||||
item_progress?: ItemProgress;
|
||||
module_type: number;
|
||||
weapon_module?: WeaponModule;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface BasicModule {
|
||||
avatar: BasicModuleAvatar;
|
||||
custom_items: BasicModuleCustomItem[];
|
||||
custom_title: string;
|
||||
info: Info[];
|
||||
name: string;
|
||||
role_id: string;
|
||||
subtitle: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface BasicModuleAvatar {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface BasicModuleCustomItem {
|
||||
is_main: boolean;
|
||||
key: string;
|
||||
value: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Info {
|
||||
main_value: string;
|
||||
name: string;
|
||||
sub_value: string;
|
||||
value: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface CharacterModule {
|
||||
custom_title: string;
|
||||
list: CharacterModuleList[];
|
||||
total: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface CharacterModuleList {
|
||||
grade: string;
|
||||
image: PurpleImage;
|
||||
level: number;
|
||||
name: string;
|
||||
talent_level: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface PurpleImage {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface EpisodeModule {
|
||||
custom_items: EpisodeModuleCustomItem[];
|
||||
custom_title: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface EpisodeModuleCustomItem {
|
||||
is_main: boolean;
|
||||
key: string;
|
||||
value: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface ItemProgress {
|
||||
custom_title: string;
|
||||
list: ItemProgressList[];
|
||||
table_tabs: string[];
|
||||
total: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface ItemProgressList {
|
||||
avatar: ListAvatar;
|
||||
name: string;
|
||||
progress: Progress;
|
||||
sort: Sort;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface ListAvatar {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Progress {
|
||||
current: number;
|
||||
max: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Sort {
|
||||
icon: Icon;
|
||||
value: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Icon {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface WeaponModule {
|
||||
custom_title: string;
|
||||
list: WeaponModuleList[];
|
||||
total: number;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface WeaponModuleList {
|
||||
grade: string;
|
||||
image: FluffyImage;
|
||||
level: number;
|
||||
name: string;
|
||||
props: string[];
|
||||
rarity: Rarity;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface FluffyImage {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Rarity {
|
||||
color: string;
|
||||
medium_url: string;
|
||||
original_format: string;
|
||||
original_url: string;
|
||||
small_url: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface Sharing {
|
||||
description: string;
|
||||
image: null;
|
||||
moment_params: MomentParams;
|
||||
qr_code: string;
|
||||
title: string;
|
||||
url: string;
|
||||
[property: string]: any;
|
||||
}
|
||||
|
||||
export interface MomentParams {
|
||||
app_id: number;
|
||||
group_label_id: number;
|
||||
hashtag_ids: number[];
|
||||
[property: string]: any;
|
||||
}
|
195
src/plugin/canvas.ts
Normal file
195
src/plugin/canvas.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
import { createCanvas, loadImage, GlobalFonts } from '@napi-rs/canvas';
|
||||
|
||||
interface MenuCommand {
|
||||
command: string;
|
||||
description: string;
|
||||
highlight?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999帮助菜单图片 (自适应美化版)
|
||||
* @returns 生成的图片的base64编码
|
||||
*/
|
||||
export async function generate1999HelpMenu(): Promise<string> {
|
||||
try {
|
||||
// 字体注册
|
||||
const fontsToTry = [
|
||||
{ path: 'C:\\Windows\\Fonts\\msyh.ttc', name: 'Microsoft YaHei' },
|
||||
{ path: 'C:\\Windows\\Fonts\\msyhbd.ttc', name: 'Microsoft YaHei Bold' },
|
||||
{ path: 'C:\\Windows\\Fonts\\simhei.ttf', name: 'SimHei' }
|
||||
];
|
||||
let fontFamily = 'sans-serif';
|
||||
let fontFamilyBold = 'sans-serif';
|
||||
for (const font of fontsToTry) {
|
||||
try {
|
||||
if (!GlobalFonts.has(font.name)) {
|
||||
GlobalFonts.registerFromPath(font.path, font.name);
|
||||
}
|
||||
if (font.name.includes('Bold')) {
|
||||
fontFamilyBold = font.name;
|
||||
} else if (fontFamily === 'sans-serif') {
|
||||
fontFamily = font.name;
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
if (fontFamilyBold === 'sans-serif') fontFamilyBold = fontFamily;
|
||||
|
||||
// 画布设置
|
||||
const width = 2560;
|
||||
const height = 1440;
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
|
||||
// 背景处理
|
||||
const backgroundPath = "E:\\NewDevelop\\NapCatQQ\\src\\canvas\\image\\normal\\01.jpg";
|
||||
try {
|
||||
const backgroundImage = await loadImage(backgroundPath);
|
||||
const scale = Math.max(width / backgroundImage.width, height / backgroundImage.height);
|
||||
const scaledWidth = backgroundImage.width * scale;
|
||||
const scaledHeight = backgroundImage.height * scale;
|
||||
const x = (width - scaledWidth) / 2;
|
||||
const y = (height - scaledHeight) / 2;
|
||||
ctx.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight);
|
||||
ctx.save();
|
||||
ctx.filter = 'blur(20px) brightness(0.75)';
|
||||
ctx.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight);
|
||||
ctx.restore();
|
||||
} catch {
|
||||
const gradient = ctx.createLinearGradient(0, 0, width, height);
|
||||
gradient.addColorStop(0, '#2a2a40');
|
||||
gradient.addColorStop(1, '#4a3a60');
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
}
|
||||
// 半透明叠加层
|
||||
ctx.fillStyle = 'rgba(15, 15, 25, 0.65)';
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
|
||||
// 命令列表
|
||||
const commands: MenuCommand[] = [
|
||||
{ command: '#1999 绑定 <TapTap ID>', description: '将您的 TapTap ID 与机器人绑定', highlight: true },
|
||||
{ command: '#1999 切换 <TapTap ID>', description: '切换当前操作的 TapTap ID' },
|
||||
{ command: '#1999 删除 <TapTap ID>', description: '解除指定的 TapTap ID 绑定' },
|
||||
{ command: '#1999 账号', description: '查看所有已绑定的 TapTap 账号', highlight: true },
|
||||
{ command: '#1999 信息', description: '查询当前选中账号的游戏信息', highlight: true },
|
||||
{ command: '#1999 心相', description: '浏览当前账号拥有的心相详情' },
|
||||
{ command: '#1999 角色', description: '浏览当前账号拥有的角色详情' },
|
||||
{ command: '#1999 帮助', description: '显示此帮助菜单' }
|
||||
];
|
||||
|
||||
// 动态计算卡片宽度
|
||||
ctx.font = `bold 40px ${fontFamilyBold}`;
|
||||
let maxCommandWidth = 0;
|
||||
let maxDescWidth = 0;
|
||||
for (const cmd of commands) {
|
||||
maxCommandWidth = Math.max(maxCommandWidth, ctx.measureText(cmd.command).width);
|
||||
ctx.font = `32px ${fontFamily}`;
|
||||
maxDescWidth = Math.max(maxDescWidth, ctx.measureText(cmd.description).width);
|
||||
ctx.font = `bold 40px ${fontFamilyBold}`;
|
||||
}
|
||||
const baseCardWidth = Math.max(maxCommandWidth, maxDescWidth) + 120;
|
||||
const minCardWidth = 420;
|
||||
const maxCardWidth = Math.min(baseCardWidth, width * 0.38);
|
||||
const cardWidth = Math.max(minCardWidth, Math.min(maxCardWidth, baseCardWidth));
|
||||
|
||||
// 卡片参数
|
||||
const cardHeight = Math.floor(height * 0.07) + 44;
|
||||
const cardBorderRadius = 24;
|
||||
const cardShadow = 'rgba(60, 40, 120, 0.18)';
|
||||
const textPaddingLeft = 38;
|
||||
// 自适应间距,最大不超过指定值
|
||||
const maxColGap = 44;
|
||||
const maxRowGap = 32;
|
||||
const minColGap = 24;
|
||||
const minRowGap = 18;
|
||||
|
||||
// 动态计算列数,保证整体不空旷且不挤
|
||||
let cols = Math.min(commands.length, Math.floor((width - 160) / (cardWidth + minColGap)));
|
||||
cols = Math.max(1, cols);
|
||||
let colGap = Math.floor((width - cols * cardWidth) / (cols + 1));
|
||||
colGap = Math.max(minColGap, Math.min(colGap, maxColGap));
|
||||
const rows = Math.ceil(commands.length / cols);
|
||||
let rowGap = Math.floor((height - rows * cardHeight - 120) / (rows + 1));
|
||||
rowGap = Math.max(minRowGap, Math.min(rowGap, maxRowGap));
|
||||
|
||||
// 计算整体卡片区尺寸,实现居中
|
||||
const cardsAreaWidth = cols * cardWidth + (cols - 1) * colGap;
|
||||
const cardsAreaHeight = rows * cardHeight + (rows - 1) * rowGap;
|
||||
const cardsStartX = Math.floor((width - cardsAreaWidth) / 2);
|
||||
const cardsStartY = Math.floor((height - cardsAreaHeight) / 2);
|
||||
|
||||
// 绘制命令卡片
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
|
||||
for (let i = 0; i < commands.length; i++) {
|
||||
const cmd = commands[i];
|
||||
if (!cmd) continue;
|
||||
const col = i % cols;
|
||||
const row = Math.floor(i / cols);
|
||||
const x = cardsStartX + col * (cardWidth + colGap);
|
||||
const y = cardsStartY + row * (cardHeight + rowGap);
|
||||
|
||||
// 卡片阴影
|
||||
ctx.save();
|
||||
ctx.shadowColor = cardShadow;
|
||||
ctx.shadowBlur = 16;
|
||||
ctx.shadowOffsetY = 6;
|
||||
|
||||
// 卡片背景
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, cardWidth, cardHeight, cardBorderRadius);
|
||||
ctx.closePath();
|
||||
if (cmd.highlight) {
|
||||
const cardGradient = ctx.createLinearGradient(x, y, x + cardWidth, y);
|
||||
cardGradient.addColorStop(0, 'rgba(110, 80, 250, 0.60)');
|
||||
cardGradient.addColorStop(1, 'rgba(150, 110, 255, 0.72)');
|
||||
ctx.fillStyle = cardGradient;
|
||||
} else {
|
||||
ctx.fillStyle = 'rgba(45, 45, 65, 0.89)';
|
||||
}
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
|
||||
// 左侧高亮条
|
||||
if (cmd.highlight) {
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, cardWidth, cardHeight, cardBorderRadius);
|
||||
ctx.clip();
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.fillRect(x, y, 12, cardHeight);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// 文本
|
||||
const commandTextX = x + textPaddingLeft;
|
||||
const commandTextY = y + cardHeight * 0.38;
|
||||
const descriptionTextY = y + cardHeight * 0.74;
|
||||
|
||||
ctx.fillStyle = cmd.highlight ? '#f0e8ff' : '#c0d4ff';
|
||||
ctx.font = `bold 40px ${fontFamilyBold}`;
|
||||
ctx.fillText(cmd.command, commandTextX, commandTextY);
|
||||
|
||||
ctx.fillStyle = cmd.highlight ? 'rgba(255,255,255,1)' : 'rgba(225,230,245,0.92)';
|
||||
ctx.font = `32px ${fontFamily}`;
|
||||
ctx.fillText(cmd.description, commandTextX, descriptionTextY);
|
||||
}
|
||||
|
||||
// 底部 NapCat & Plugin
|
||||
const bottomTextY = height - 36;
|
||||
ctx.font = `23px ${fontFamily}`;
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.62)';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'bottom';
|
||||
ctx.fillText('NapCat & Plugin', width / 2, bottomTextY);
|
||||
|
||||
// 转换为base64
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
const base64Image = `base64://${buffer.toString('base64')}`;
|
||||
return base64Image;
|
||||
} catch (error) {
|
||||
console.error('生成菜单时发生错误:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
25
src/plugin/get_user.ts
Normal file
25
src/plugin/get_user.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { RequestUtil } from '@/common/request';
|
||||
import { GameUserDetail } from './api';
|
||||
|
||||
/**
|
||||
* 获取用户游戏记录信息
|
||||
* @param tap_id TapTap用户ID
|
||||
* @returns 用户游戏记录信息
|
||||
*/
|
||||
|
||||
export async function get_user(tap_id: string): Promise<GameUserDetail> {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
'app_id': '221062',
|
||||
'user_id': tap_id,
|
||||
'X-UA': 'V=1&PN=WebApp&LANG=zh_CN&VN_CODE=102&VN=0.1.0&LOC=CN&PLT=Android&DS=Android&UID=00e000ee-00e0-0e0e-ee00-f0c95d8ca115&VID=444444444&OS=Android&OSV=14.0.1'
|
||||
});
|
||||
|
||||
const url = `https://www.taptap.cn/webapiv2/game-record/v1/detail-by-user?${params.toString()}`;
|
||||
return await RequestUtil.HttpGetJson(url, 'GET');
|
||||
} catch (error) {
|
||||
console.error('获取用户游戏记录失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
@@ -1,11 +1,219 @@
|
||||
import { NapCatOneBot11Adapter, OB11Message } from '@/onebot';
|
||||
import { NapCatOneBot11Adapter, OB11Message, OB11MessageDataType } from '@/onebot';
|
||||
import { NapCatCore } from '@/core';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
import { OB11PluginAdapter } from '@/onebot/network/plugin';
|
||||
import { TapAccountManager } from './TapAccountManager';
|
||||
import { sendMessage } from './sendMessage';
|
||||
import { get_user } from './get_user';
|
||||
import { generate1999HelpMenu } from './canvas';
|
||||
import { generate1999AccountListImage, generate1999BindImage, generate1999CharacterImage, generate1999InfoImage, generate1999SwitchImage, generate1999WeaponImage } from './new';
|
||||
|
||||
export const plugin_onmessage = async (adapter: string, _core: NapCatCore, _obCtx: NapCatOneBot11Adapter, message: OB11Message, action: ActionMap, instance: OB11PluginAdapter) => {
|
||||
if (message.raw_message === 'ping') {
|
||||
const ret = await action.get('send_group_msg')?.handle({ group_id: String(message.group_id), message: 'pong' }, adapter, instance.config);
|
||||
console.log(ret);
|
||||
const tapAccountManager = new TapAccountManager();
|
||||
|
||||
export const plugin_onmessage = async (
|
||||
_adapter: string,
|
||||
_core: NapCatCore,
|
||||
_obCtx: NapCatOneBot11Adapter,
|
||||
message: OB11Message,
|
||||
action: ActionMap,
|
||||
_instance: OB11PluginAdapter
|
||||
) => {
|
||||
if (message.raw_message.startsWith('#1999 绑定')) {
|
||||
const tap_id = message.raw_message.slice(8).trim();
|
||||
const userId = message.user_id.toString();
|
||||
|
||||
if (tap_id.length === 0) {
|
||||
await sendMessage(message, action, '请输入正确的 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 验证账号有效性并获取角色名称
|
||||
const userInfo = await get_user(tap_id);
|
||||
const characterName = userInfo.data.list[0]?.basic_module?.name;
|
||||
if (!characterName) {
|
||||
await sendMessage(message, action, '获取角色名称失败,请检查账号是否有效');
|
||||
return;
|
||||
}
|
||||
// 使用账号管理器绑定账号
|
||||
tapAccountManager.bindAccount(userId, tap_id, characterName);
|
||||
await sendMessage(message, action, [{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999BindImage(tap_id, characterName),
|
||||
summary: '绑定成功'
|
||||
}
|
||||
}]);
|
||||
} catch (error) {
|
||||
await sendMessage(message, action, `绑定失败,可能是TapTap ID无效或未关联游戏账号`);
|
||||
console.error(`绑定TapTap ID失败:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
else if (message.raw_message.startsWith('#1999 切换')) {
|
||||
const tap_id = message.raw_message.slice(8).trim();
|
||||
const userId = message.user_id.toString();
|
||||
|
||||
if (tap_id.length === 0) {
|
||||
await sendMessage(message, action, '请输入要切换的 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
// 使用账号管理器切换账号
|
||||
const result = tapAccountManager.switchAccount(userId, tap_id);
|
||||
if (!result) {
|
||||
const accountList = tapAccountManager.getAccountList(userId);
|
||||
if (!accountList.hasAccounts) {
|
||||
await sendMessage(message, action, '您尚未绑定任何账号,请先使用"#1999 绑定"命令');
|
||||
} else {
|
||||
await sendMessage(message, action, `未找到ID为 ${tap_id} 的绑定记录,请先绑定该账号`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const accountInfo = tapAccountManager.getAccountList(userId);
|
||||
const account = accountInfo.accounts?.find(a => a.id === tap_id);
|
||||
await sendMessage(message, action, [{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999SwitchImage(tap_id, account?.name ?? ''),
|
||||
summary: '切换成功'
|
||||
}
|
||||
}]);
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 删除')) {
|
||||
const tap_id = message.raw_message.slice(8).trim();
|
||||
const userId = message.user_id.toString();
|
||||
|
||||
if (tap_id.length === 0) {
|
||||
await sendMessage(message, action, '请输入要删除的 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
// 使用账号管理器删除账号
|
||||
const result = await tapAccountManager.deleteAccount(userId, tap_id);
|
||||
|
||||
if (!result.success) {
|
||||
if (result.isEmpty) {
|
||||
await sendMessage(message, action, '您尚未绑定任何账号');
|
||||
} else {
|
||||
await sendMessage(message, action, `未找到ID为 ${tap_id} 的绑定记录`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.isEmpty) {
|
||||
await sendMessage(message, action, `已删除账号 ${tap_id}(${result.deletedAccount?.name}),您当前没有绑定任何账号`);
|
||||
} else {
|
||||
await sendMessage(message, action, `已删除账号 ${tap_id}(${result.deletedAccount?.name}),当前默认账号为 ${result.defaultAccount?.id}(${result.defaultAccount?.name})`);
|
||||
}
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 账号')) {
|
||||
const userId = message.user_id.toString();
|
||||
const accountList = tapAccountManager.getAccountList(userId);
|
||||
|
||||
if (!accountList.hasAccounts) {
|
||||
await sendMessage(message, action, '您尚未绑定任何账号');
|
||||
return;
|
||||
}
|
||||
|
||||
await sendMessage(message, action, [{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999AccountListImage(accountList.accounts!),
|
||||
summary: '账号列表'
|
||||
}
|
||||
}]);
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 信息')) {
|
||||
const userId = message.user_id.toString();
|
||||
const defaultAccount = tapAccountManager.getDefaultAccount(userId);
|
||||
|
||||
if (!defaultAccount.hasDefault) {
|
||||
await sendMessage(message, action, '请先绑定 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
const tap_id = defaultAccount.tapId!;
|
||||
|
||||
try {
|
||||
const userInfo = await get_user(tap_id);
|
||||
const user_1999_name = userInfo.data.list[0]?.basic_module?.name;
|
||||
if (!user_1999_name) {
|
||||
await sendMessage(message, action, '获取账号信息失败,请检查账号是否有效');
|
||||
return;
|
||||
}
|
||||
await sendMessage(message, action, [{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999InfoImage(userInfo),
|
||||
summary: '账号信息'
|
||||
}
|
||||
}]);
|
||||
} catch (error) {
|
||||
await sendMessage(message, action, '获取账号信息失败,请检查账号是否有效');
|
||||
console.error('获取用户信息失败:', error);
|
||||
}
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 心相')) {
|
||||
const userId = message.user_id.toString();
|
||||
const defaultAccount = tapAccountManager.getDefaultAccount(userId);
|
||||
|
||||
if (!defaultAccount.hasDefault) {
|
||||
await sendMessage(message, action, '请先绑定 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
const tap_id = defaultAccount.tapId!;
|
||||
try {
|
||||
const userInfo = await get_user(tap_id);
|
||||
await sendMessage(message, action, [
|
||||
{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999WeaponImage(userInfo),
|
||||
summary: '心相信息'
|
||||
}
|
||||
}
|
||||
]);
|
||||
} catch (error) {
|
||||
await sendMessage(message, action, '获取心相信息失败,请检查账号是否有效');
|
||||
console.error('获取心相信息失败:', error);
|
||||
}
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 角色')) {
|
||||
const userId = message.user_id.toString();
|
||||
const defaultAccount = tapAccountManager.getDefaultAccount(userId);
|
||||
|
||||
if (!defaultAccount.hasDefault) {
|
||||
await sendMessage(message, action, '请先绑定 TapTap ID');
|
||||
return;
|
||||
}
|
||||
|
||||
const tap_id = defaultAccount.tapId!;
|
||||
try {
|
||||
const userInfo = await get_user(tap_id);
|
||||
const user_1999_name = userInfo.data.list[0]?.basic_module?.name;
|
||||
if (!user_1999_name) {
|
||||
await sendMessage(message, action, '获取角色信息失败,请检查账号是否有效');
|
||||
return;
|
||||
}
|
||||
await sendMessage(message, action, [
|
||||
{
|
||||
type: OB11MessageDataType.image,
|
||||
data: {
|
||||
file: await generate1999CharacterImage(userInfo),
|
||||
summary: '角色信息'
|
||||
}
|
||||
}
|
||||
]);
|
||||
} catch (error) {
|
||||
await sendMessage(message, action, '获取角色信息失败,请检查账号是否有效');
|
||||
console.error('获取角色信息失败:', error);
|
||||
}
|
||||
}
|
||||
else if (message.raw_message.startsWith('#1999 帮助') || message.raw_message.startsWith('#1999 菜单')) {
|
||||
await sendMessage(message, action, [
|
||||
{ type: OB11MessageDataType.image, data: { file: await generate1999HelpMenu() } }
|
||||
]);
|
||||
}
|
||||
};
|
387
src/plugin/new.ts
Normal file
387
src/plugin/new.ts
Normal file
@@ -0,0 +1,387 @@
|
||||
import { createCanvas, loadImage, GlobalFonts } from '@napi-rs/canvas';
|
||||
import { GameUserDetail } from './api';
|
||||
|
||||
// 字体注册工具
|
||||
function getFontFamily() {
|
||||
const fontsToTry = [
|
||||
{ path: 'C:\\Windows\\Fonts\\msyh.ttc', name: 'Microsoft YaHei' },
|
||||
{ path: 'C:\\Windows\\Fonts\\msyhbd.ttc', name: 'Microsoft YaHei Bold' },
|
||||
{ path: 'C:\\Windows\\Fonts\\simhei.ttf', name: 'SimHei' }
|
||||
];
|
||||
let fontFamily = 'sans-serif';
|
||||
let fontFamilyBold = 'sans-serif';
|
||||
for (const font of fontsToTry) {
|
||||
try {
|
||||
if (!GlobalFonts.has(font.name)) {
|
||||
GlobalFonts.registerFromPath(font.path, font.name);
|
||||
}
|
||||
if (font.name.includes('Bold')) {
|
||||
fontFamilyBold = font.name;
|
||||
} else if (fontFamily === 'sans-serif') {
|
||||
fontFamily = font.name;
|
||||
}
|
||||
} catch { }
|
||||
}
|
||||
if (fontFamilyBold === 'sans-serif') fontFamilyBold = fontFamily;
|
||||
return { fontFamily, fontFamilyBold };
|
||||
}
|
||||
|
||||
// 背景绘制工具
|
||||
async function drawBackground(ctx: any, width: number, height: number) {
|
||||
const backgroundPath = "E:\\NewDevelop\\NapCatQQ\\src\\canvas\\image\\normal\\01.jpg";
|
||||
try {
|
||||
const backgroundImage = await loadImage(backgroundPath);
|
||||
const scale = Math.max(width / backgroundImage.width, height / backgroundImage.height);
|
||||
const scaledWidth = backgroundImage.width * scale;
|
||||
const scaledHeight = backgroundImage.height * scale;
|
||||
const x = (width - scaledWidth) / 2;
|
||||
const y = (height - scaledHeight) / 2;
|
||||
ctx.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight);
|
||||
ctx.save();
|
||||
ctx.filter = 'blur(20px) brightness(0.75)';
|
||||
ctx.drawImage(backgroundImage, x, y, scaledWidth, scaledHeight);
|
||||
ctx.restore();
|
||||
} catch {
|
||||
const gradient = ctx.createLinearGradient(0, 0, width, height);
|
||||
gradient.addColorStop(0, '#2a2a40');
|
||||
gradient.addColorStop(1, '#4a3a60');
|
||||
ctx.fillStyle = gradient;
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
}
|
||||
ctx.fillStyle = 'rgba(15, 15, 25, 0.65)';
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
}
|
||||
|
||||
// 标题美化工具
|
||||
function drawTitle(ctx: any, text: string, width: number, y: number, fontFamilyBold: string) {
|
||||
// 小标题条
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.32;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.fillRect(width / 2 - 220, y - 38, 440, 54);
|
||||
ctx.restore();
|
||||
// 标题
|
||||
ctx.font = `bold 44px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#f0e8ff';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(text, width / 2, y);
|
||||
// 下划线
|
||||
ctx.save();
|
||||
ctx.strokeStyle = '#c5a8ff';
|
||||
ctx.lineWidth = 3;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(width / 2 - 80, y + 18);
|
||||
ctx.lineTo(width / 2 + 80, y + 18);
|
||||
ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// 信息行绘制
|
||||
function drawInfoLine(ctx: any, text: string, x: number, y: number, font: string, color: string | CanvasGradient | CanvasPattern) {
|
||||
ctx.font = font;
|
||||
// 兼容 CanvasGradient/CanvasPattern 和 string
|
||||
if (typeof color === 'string' || color instanceof CanvasGradient || color instanceof CanvasPattern) {
|
||||
ctx.fillStyle = color;
|
||||
} else {
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
}
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(text, x, y);
|
||||
}
|
||||
|
||||
// 卡片小块绘制
|
||||
function drawMiniCard(ctx: any, x: number, y: number, w: number, h: number, radius: number, shadow = true, color?: string, shadowColor?: string) {
|
||||
ctx.save();
|
||||
if (shadow) {
|
||||
ctx.shadowColor = shadowColor ?? 'rgba(60, 40, 120, 0.13)';
|
||||
ctx.shadowBlur = 12;
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, w, h, radius);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = color ?? 'rgba(45, 45, 65, 0.89)';
|
||||
ctx.fill();
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// 底部标识
|
||||
function drawFooter(ctx: any, width: number, height: number, fontFamily: string) {
|
||||
ctx.font = `22px ${fontFamily}`;
|
||||
ctx.fillStyle = 'rgba(255,255,255,0.62)';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'bottom';
|
||||
ctx.fillText('NapCat & Plugin', width / 2, height - 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999 信息图片
|
||||
*/
|
||||
export async function generate1999InfoImage(userInfo: any): Promise<string> {
|
||||
const { fontFamily, fontFamilyBold } = getFontFamily();
|
||||
const width = 2560, height = 1440;
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
await drawBackground(ctx, width, height);
|
||||
|
||||
// 标题
|
||||
drawTitle(ctx, '账号信息', width, 120, fontFamilyBold);
|
||||
|
||||
// 信息内容
|
||||
const startX = width / 2 - 350, startY = 220, lineH = 62;
|
||||
const infoList = [
|
||||
`昵称: ${userInfo.data.list[0]?.basic_module?.name ?? '-'}`,
|
||||
`角色ID: ${userInfo.data.list[0]?.basic_module?.role_id ?? '-'}`,
|
||||
`角色数量: ${userInfo.data.list[0]?.basic_module?.custom_items[0]?.value ?? '-'}`,
|
||||
`登录天数: ${userInfo.data.list[0]?.basic_module?.custom_items[1]?.value ?? '-'}`,
|
||||
`雨滴数量: ${userInfo.data.list[0]?.basic_module?.custom_items[2]?.value ?? '-'}`,
|
||||
`你何时睁眼看这个世界: ${userInfo.data.list[1]?.episode_module?.custom_items[0]?.value ?? '-'}`,
|
||||
`你在哪一幕: ${userInfo.data.list[1]?.episode_module?.custom_items[1]?.value ?? '-'}`,
|
||||
`人工梦游: ${userInfo.data.list[1]?.episode_module?.custom_items[2]?.value ?? '-'}`,
|
||||
];
|
||||
ctx.font = `bold 36px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
infoList.forEach((txt, i) => {
|
||||
drawInfoLine(ctx, txt, startX, startY + i * lineH, ctx.font, ctx.fillStyle);
|
||||
});
|
||||
|
||||
drawFooter(ctx, width, height, fontFamily);
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
return `base64://${buffer.toString('base64')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999 心相图片
|
||||
*/
|
||||
export async function generate1999WeaponImage(userInfo: GameUserDetail): Promise<string> {
|
||||
const { fontFamily, fontFamilyBold } = getFontFamily();
|
||||
const width = 2560, height = 1440;
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
await drawBackground(ctx, width, height);
|
||||
|
||||
drawTitle(ctx, '心相', width, 120, fontFamilyBold);
|
||||
|
||||
ctx.font = `bold 34px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
drawInfoLine(ctx, `昵称: ${userInfo.data.list[0]?.basic_module?.name ?? '-'}`, width / 2 - 350, 180, ctx.font, ctx.fillStyle);
|
||||
drawInfoLine(ctx, `角色ID: ${userInfo.data.list[0]?.basic_module?.role_id ?? '-'}`, width / 2 - 350, 230, ctx.font, ctx.fillStyle);
|
||||
|
||||
const weaponList = userInfo.data.list[3]?.weapon_module?.list ?? [];
|
||||
const cardW = 420, cardH = 110, gapX = 38, gapY = 32;
|
||||
const imgSize = 90;
|
||||
const textLeft = 36 + imgSize + 18; // 缩略图+间隔
|
||||
const cols = Math.min(5, Math.floor((width - 2 * gapX) / (cardW + gapX)));
|
||||
const areaW = cols * cardW + (cols - 1) * gapX;
|
||||
const startX = (width - areaW) / 2;
|
||||
let y = 280;
|
||||
ctx.font = `bold 32px ${fontFamilyBold}`;
|
||||
for (let idx = 0; idx < weaponList.length; idx++) {
|
||||
const item = weaponList[idx];
|
||||
const col = idx % cols, row = Math.floor(idx / cols);
|
||||
const x = startX + col * (cardW + gapX);
|
||||
const cy = y + row * (cardH + gapY);
|
||||
drawMiniCard(ctx, x, cy, cardW, cardH, 22);
|
||||
|
||||
if (!item) continue; // 跳过空值
|
||||
// 绘制缩略图
|
||||
if (item.image?.small_url) {
|
||||
try {
|
||||
const img = await loadImage(item.image.small_url);
|
||||
const imgX = x + 18;
|
||||
const imgY = cy + (cardH - imgSize) / 2;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.arc(imgX + imgSize / 2, imgY + imgSize / 2, imgSize / 2, 0, Math.PI * 2);
|
||||
ctx.closePath();
|
||||
ctx.clip();
|
||||
ctx.drawImage(img, imgX, imgY, imgSize, imgSize);
|
||||
ctx.restore();
|
||||
} catch { }
|
||||
}
|
||||
|
||||
ctx.fillStyle = '#f0e8ff';
|
||||
ctx.font = `bold 32px ${fontFamilyBold}`;
|
||||
ctx.fillText(item.name ?? '-', x + textLeft, cy + cardH / 2 - 12);
|
||||
ctx.font = `28px ${fontFamily}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.fillText(`LV.${item.level ?? '-'}`, x + textLeft, cy + cardH / 2 + 32);
|
||||
}
|
||||
|
||||
drawFooter(ctx, width, height, fontFamily);
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
return `base64://${buffer.toString('base64')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999 角色图片
|
||||
*/
|
||||
export async function generate1999CharacterImage(userInfo: GameUserDetail): Promise<string> {
|
||||
const { fontFamily, fontFamilyBold } = getFontFamily();
|
||||
const width = 2560, height = 1440;
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
await drawBackground(ctx, width, height);
|
||||
|
||||
drawTitle(ctx, '角色', width, 120, fontFamilyBold);
|
||||
|
||||
ctx.font = `bold 34px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
drawInfoLine(ctx, `昵称: ${userInfo.data.list[0]?.basic_module?.name ?? '-'}`, width / 2 - 350, 180, ctx.font, ctx.fillStyle);
|
||||
drawInfoLine(ctx, `角色ID: ${userInfo.data.list[0]?.basic_module?.role_id ?? '-'}`, width / 2 - 350, 230, ctx.font, ctx.fillStyle);
|
||||
|
||||
const charList = userInfo.data.list[2]?.character_module?.list ?? [];
|
||||
const cardW = 420, cardH = 110, gapX = 38, gapY = 32;
|
||||
const imgSize = 90;
|
||||
const textLeft = 36 + imgSize + 18;
|
||||
const cols = Math.min(5, Math.floor((width - 2 * gapX) / (cardW + gapX)));
|
||||
const areaW = cols * cardW + (cols - 1) * gapX;
|
||||
const startX = (width - areaW) / 2;
|
||||
let y = 280;
|
||||
ctx.font = `bold 32px ${fontFamilyBold}`;
|
||||
for (let idx = 0; idx < charList.length; idx++) {
|
||||
const item = charList[idx];
|
||||
const col = idx % cols, row = Math.floor(idx / cols);
|
||||
const x = startX + col * (cardW + gapX);
|
||||
const cy = y + row * (cardH + gapY);
|
||||
drawMiniCard(ctx, x, cy, cardW, cardH, 22);
|
||||
|
||||
// 绘制缩略图
|
||||
if (!item) continue; // 跳过空值
|
||||
if (item.image?.small_url) {
|
||||
try {
|
||||
const img = await loadImage(item.image.small_url);
|
||||
const imgX = x + 18;
|
||||
const imgY = cy + (cardH - imgSize) / 2;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
ctx.arc(imgX + imgSize / 2, imgY + imgSize / 2, imgSize / 2, 0, Math.PI * 2);
|
||||
ctx.closePath();
|
||||
ctx.clip();
|
||||
ctx.drawImage(img, imgX, imgY, imgSize, imgSize);
|
||||
ctx.restore();
|
||||
} catch { }
|
||||
}
|
||||
|
||||
ctx.fillStyle = '#f0e8ff';
|
||||
ctx.font = `bold 32px ${fontFamilyBold}`;
|
||||
ctx.fillText(item.name ?? '-', x + textLeft, cy + cardH / 2 - 12);
|
||||
ctx.font = `28px ${fontFamily}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.fillText(`LV.${item.level ?? '-'}`, x + textLeft, cy + cardH / 2 + 32);
|
||||
}
|
||||
|
||||
drawFooter(ctx, width, height, fontFamily);
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
return `base64://${buffer.toString('base64')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999 绑定/切换结果图片
|
||||
*/
|
||||
async function generateSimpleResultImage(title: string, tapId: string, characterName: string): Promise<string> {
|
||||
const { fontFamily, fontFamilyBold } = getFontFamily();
|
||||
const width = 900, height = 340;
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
await drawBackground(ctx, width, height);
|
||||
|
||||
// 标题
|
||||
drawTitle(ctx, title, width, 80, fontFamilyBold);
|
||||
|
||||
// 内容卡片
|
||||
const cardW = 700, cardH = 120, cardX = (width - cardW) / 2, cardY = 120;
|
||||
drawMiniCard(
|
||||
ctx,
|
||||
cardX,
|
||||
cardY,
|
||||
cardW,
|
||||
cardH,
|
||||
20,
|
||||
true,
|
||||
'rgba(197,168,255,0.18)',
|
||||
'rgba(197,168,255,0.13)'
|
||||
);
|
||||
|
||||
// TapTap ID
|
||||
ctx.font = `bold 28px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(`TapTap ID:`, cardX + 36, cardY + 48);
|
||||
ctx.font = `bold 28px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#fffbe6';
|
||||
ctx.fillText(tapId, cardX + 180, cardY + 48);
|
||||
|
||||
// 角色名称
|
||||
ctx.font = `bold 28px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#c5a8ff';
|
||||
ctx.fillText(`角色名称:`, cardX + 36, cardY + 88);
|
||||
ctx.font = `bold 28px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#ffe066';
|
||||
ctx.fillText(characterName, cardX + 180, cardY + 88);
|
||||
|
||||
drawFooter(ctx, width, height, fontFamily);
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
return `base64://${buffer.toString('base64')}`;
|
||||
}
|
||||
|
||||
export async function generate1999BindImage(tapId: string, characterName: string): Promise<string> {
|
||||
return generateSimpleResultImage('绑定成功', tapId, characterName);
|
||||
}
|
||||
|
||||
export async function generate1999SwitchImage(tapId: string, characterName: string): Promise<string> {
|
||||
return generateSimpleResultImage('切换成功', tapId, characterName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成REVERSE.1999 账号列表图片
|
||||
*/
|
||||
export async function generate1999AccountListImage(accountList: { id: string, name: string, isDefault?: boolean }[]): Promise<string> {
|
||||
const { fontFamily, fontFamilyBold } = getFontFamily();
|
||||
const width = 900;
|
||||
const cardW = 700, cardH = 56, gapY = 18;
|
||||
const listH = accountList.length * cardH + (accountList.length - 1) * gapY;
|
||||
const height = Math.max(340, 120 + listH + 60);
|
||||
const canvas = createCanvas(width, height);
|
||||
const ctx = canvas.getContext('2d');
|
||||
await drawBackground(ctx, width, height);
|
||||
|
||||
// 标题
|
||||
drawTitle(ctx, '已绑定账号列表', width, 80, fontFamilyBold);
|
||||
|
||||
// 列表区域起始Y,垂直居中
|
||||
const startY = Math.max(140, (height - listH) / 2);
|
||||
|
||||
for (let i = 0; i < accountList.length; i++) {
|
||||
const item = accountList[i];
|
||||
if (!item) continue; // 跳过空值
|
||||
const x = (width - cardW) / 2;
|
||||
const y = startY + i * (cardH + gapY);
|
||||
|
||||
// 卡片颜色
|
||||
const cardColor = item.isDefault ? 'rgba(255, 224, 102, 0.22)' : 'rgba(197, 168, 255, 0.18)';
|
||||
const shadowColor = item.isDefault ? 'rgba(255, 224, 102, 0.18)' : 'rgba(197, 168, 255, 0.13)';
|
||||
drawMiniCard(ctx, x, y, cardW, cardH, 16, true, cardColor, shadowColor);
|
||||
|
||||
// 账号ID(小号,灰色)
|
||||
ctx.font = `22px ${fontFamily}`;
|
||||
ctx.fillStyle = '#b0b0c8';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(`ID: ${item.id}`, x + 28, y + 26);
|
||||
|
||||
// 账号名(大号,主色)
|
||||
ctx.font = `bold 26px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = item.isDefault ? '#ffe066' : '#c5a8ff';
|
||||
ctx.fillText(item.name, x + 28, y + 48);
|
||||
|
||||
// 当前使用标识
|
||||
if (item.isDefault) {
|
||||
ctx.font = `bold 18px ${fontFamilyBold}`;
|
||||
ctx.fillStyle = '#fffbe6';
|
||||
ctx.fillText('(当前使用)', x + 28 + ctx.measureText(item.name).width + 12, y + 48);
|
||||
}
|
||||
}
|
||||
|
||||
drawFooter(ctx, width, height, fontFamily);
|
||||
const buffer = canvas.toBuffer('image/png');
|
||||
return `base64://${buffer.toString('base64')}`;
|
||||
}
|
23
src/plugin/sendMessage.ts
Normal file
23
src/plugin/sendMessage.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { OB11Message, OB11MessageData } from '@/onebot';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
|
||||
/**
|
||||
* 发送消息工具函数
|
||||
*/
|
||||
export async function sendMessage<T extends OB11MessageData[] | string>(
|
||||
message: OB11Message,
|
||||
action: ActionMap,
|
||||
content: T
|
||||
) {
|
||||
if (message.message_type === 'private') {
|
||||
await action.get('send_msg')?._handle({
|
||||
user_id: message.user_id.toString(),
|
||||
message: content,
|
||||
});
|
||||
} else {
|
||||
await action.get('send_msg')?._handle({
|
||||
group_id: message.group_id?.toString(),
|
||||
message: content,
|
||||
});
|
||||
}
|
||||
};
|
@@ -1,7 +1,6 @@
|
||||
import { LogWrapper } from '@/common/log';
|
||||
import * as net from 'net';
|
||||
import * as process from 'process';
|
||||
import { Writable } from 'stream';
|
||||
|
||||
/**
|
||||
* 连接到命名管道并重定向stdout
|
||||
@@ -26,50 +25,12 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
||||
}, timeoutMs);
|
||||
|
||||
try {
|
||||
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
let originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
const pipeSocket = net.connect(pipePath, () => {
|
||||
// 清除超时
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
// 优化网络性能设置
|
||||
pipeSocket.setNoDelay(true); // 减少延迟
|
||||
|
||||
// 设置更高的高水位线,允许更多数据缓冲
|
||||
|
||||
logger.log(`[StdOut] 已重定向到命名管道: ${pipePath}`);
|
||||
|
||||
// 创建拥有更优雅背压处理的 Writable 流
|
||||
const pipeWritable = new Writable({
|
||||
highWaterMark: 1024 * 64, // 64KB 高水位线
|
||||
write(chunk, encoding, callback) {
|
||||
if (!pipeSocket.writable) {
|
||||
// 如果管道不可写,退回到原始stdout
|
||||
logger.log('[StdOut] 管道不可写,回退到控制台输出');
|
||||
return originalStdoutWrite(chunk, encoding, callback);
|
||||
}
|
||||
|
||||
// 尝试写入数据到管道
|
||||
const canContinue = pipeSocket.write(chunk, encoding, () => {
|
||||
// 数据已被发送或放入内部缓冲区
|
||||
});
|
||||
|
||||
if (canContinue) {
|
||||
// 如果返回true,表示可以继续写入更多数据
|
||||
// 立即通知写入流可以继续
|
||||
process.nextTick(callback);
|
||||
} else {
|
||||
// 如果返回false,表示内部缓冲区已满
|
||||
// 等待drain事件再恢复写入
|
||||
pipeSocket.once('drain', () => {
|
||||
callback();
|
||||
});
|
||||
}
|
||||
// 明确返回true,表示写入已处理
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
// 重定向stdout
|
||||
process.stdout.write = (
|
||||
chunk: any,
|
||||
encoding?: BufferEncoding | (() => void),
|
||||
@@ -79,11 +40,8 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
||||
cb = encoding;
|
||||
encoding = undefined;
|
||||
}
|
||||
|
||||
// 使用优化的writable流处理写入
|
||||
return pipeWritable.write(chunk, encoding as BufferEncoding, cb as () => void);
|
||||
return pipeSocket.write(chunk, encoding as BufferEncoding, cb);
|
||||
};
|
||||
|
||||
// 提供断开连接的方法
|
||||
const disconnect = () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
@@ -95,7 +53,6 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
||||
resolve({ disconnect });
|
||||
});
|
||||
|
||||
// 管道错误处理
|
||||
pipeSocket.on('error', (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
@@ -103,18 +60,11 @@ export function connectToNamedPipe(logger: LogWrapper, timeoutMs: number = 5000)
|
||||
reject(err);
|
||||
});
|
||||
|
||||
// 管道关闭处理
|
||||
pipeSocket.on('end', () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
logger.log('命名管道连接已关闭');
|
||||
});
|
||||
|
||||
// 确保在连接意外关闭时恢复stdout
|
||||
pipeSocket.on('close', () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
logger.log('命名管道连接已关闭');
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
clearTimeout(timeoutId);
|
||||
logger.log(`尝试连接命名管道 ${pipePath} 时发生异常:`, error);
|
||||
|
@@ -7,7 +7,8 @@ import { builtinModules } from 'module';
|
||||
const external = [
|
||||
'silk-wasm',
|
||||
'ws',
|
||||
'express'
|
||||
'express',
|
||||
'@napi-rs/canvas'
|
||||
];
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
|
||||
|
Reference in New Issue
Block a user