mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
113 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
4bd92a72bd | ||
![]() |
a3be26f3e4 | ||
![]() |
675c906cbf | ||
![]() |
6be6023236 | ||
![]() |
42cee0d018 | ||
![]() |
041f725748 | ||
![]() |
0594d61631 | ||
![]() |
15cae6b765 | ||
![]() |
b984116c35 | ||
![]() |
13bda6e3f4 | ||
![]() |
c0d18549d1 | ||
![]() |
3caff72fce | ||
![]() |
1313e9c3f4 | ||
![]() |
0848d5a39e | ||
![]() |
7660646059 | ||
![]() |
bcd90fc744 | ||
![]() |
638fc22d62 | ||
![]() |
c87d365b88 | ||
![]() |
aee9602f25 | ||
![]() |
976fbd0220 | ||
![]() |
afd955d06f | ||
![]() |
4d548da66b | ||
![]() |
41b70f53d1 | ||
![]() |
a47a618bcd | ||
![]() |
62170a30af | ||
![]() |
780c5ac23c | ||
![]() |
9fba519a5a | ||
![]() |
3cd0e7d26b | ||
![]() |
a8fd6af994 | ||
![]() |
4000b89644 | ||
![]() |
9c00bbc0b7 | ||
![]() |
a2989d3b38 | ||
![]() |
fc731b60d5 | ||
![]() |
193980dd4a | ||
![]() |
35427b0768 | ||
![]() |
73ea130e40 | ||
![]() |
5667e6aaee | ||
![]() |
fbd626131d | ||
![]() |
7b82444338 | ||
![]() |
8108b9f565 | ||
![]() |
c6ddd00cd9 | ||
![]() |
20c0c00fa0 | ||
![]() |
1f90364ba6 | ||
![]() |
49ea4d31a5 | ||
![]() |
dc35f1456a | ||
![]() |
0ebeb90804 | ||
![]() |
3ef5436c98 | ||
![]() |
de7996d789 | ||
![]() |
ac52d9bae2 | ||
![]() |
cb02df3b76 | ||
![]() |
5fc5a6f1a6 | ||
![]() |
726a0d0394 | ||
![]() |
6edf5345a3 | ||
![]() |
242bbfdb14 | ||
![]() |
89e7712676 | ||
![]() |
9525786929 | ||
![]() |
72088e41a8 | ||
![]() |
a3ed9ff2ef | ||
![]() |
ff16dc73ec | ||
![]() |
2da4ef5f0f | ||
![]() |
eaf481799d | ||
![]() |
1f72863aba | ||
![]() |
6b353fd8d8 | ||
![]() |
56cde4ad79 | ||
![]() |
3b86d3c632 | ||
![]() |
4ac7a25afb | ||
![]() |
8248011a12 | ||
![]() |
5f454456d2 | ||
![]() |
e99a619c23 | ||
![]() |
1fc791bb68 | ||
![]() |
f1d83f7c16 | ||
![]() |
527bb72bcf | ||
![]() |
d78409fd07 | ||
![]() |
d5e7e8944f | ||
![]() |
fb405a5c1c | ||
![]() |
a9e471deca | ||
![]() |
9cd15ae337 | ||
![]() |
8ed4cc4b0a | ||
![]() |
a62de441cf | ||
![]() |
02a8999410 | ||
![]() |
59c7979d69 | ||
![]() |
bb7b28cd8f | ||
![]() |
056497b98a | ||
![]() |
ac2fb032c4 | ||
![]() |
c933bdd5d9 | ||
![]() |
89c71a58fa | ||
![]() |
27ba85b4ff | ||
![]() |
79a75fed8e | ||
![]() |
ee7a76b29f | ||
![]() |
c53bdc3ce0 | ||
![]() |
f36e328751 | ||
![]() |
871b5688c2 | ||
![]() |
b96076b297 | ||
![]() |
d4488e40cf | ||
![]() |
7e61497243 | ||
![]() |
e71ccdd12a | ||
![]() |
202129d491 | ||
![]() |
a1700dd503 | ||
![]() |
2954776539 | ||
![]() |
fb1f122ef7 | ||
![]() |
96c63e4689 | ||
![]() |
c94936d3dc | ||
![]() |
8c22f11087 | ||
![]() |
8a089c84a9 | ||
![]() |
b631e6f8a2 | ||
![]() |
b3b48b032c | ||
![]() |
f3e8230eca | ||
![]() |
cc9adf9d40 | ||
![]() |
15a640d1dc | ||
![]() |
c25b9f86db | ||
![]() |
ecfd033afb | ||
![]() |
f3ed8c7dff | ||
![]() |
6089046721 |
@@ -1,6 +1,6 @@
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
@@ -32,6 +32,8 @@ NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
|
||||
|
||||
[Server.Other](https://docs.napcat.cyou/)
|
||||
|
||||
[Qbot.News](https://neko.qbot.news)
|
||||
|
||||
## 回家旅途
|
||||
[QQ Group#1](https://qm.qq.com/q/I6LU87a0Yq)
|
||||
|
||||
|
BIN
external/logo.png
vendored
Normal file
BIN
external/logo.png
vendored
Normal file
Binary file not shown.
After Width: | Height: | Size: 204 KiB |
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "qq-chat",
|
||||
"version": "9.9.16-29927",
|
||||
"verHash": "3e273e30",
|
||||
"linuxVersion": "3.2.13-29927",
|
||||
"linuxVerHash": "833d113c",
|
||||
"version": "9.9.17-30899",
|
||||
"verHash": "ececf273",
|
||||
"linuxVersion": "3.2.15-30899",
|
||||
"linuxVerHash": "63c751e8",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"description": "QQ",
|
||||
@@ -18,7 +18,7 @@
|
||||
"qd": "externals/devtools/cli/index.js"
|
||||
},
|
||||
"main": "./loadNapCat.js",
|
||||
"buildVersion": "29927",
|
||||
"buildVersion": "30899",
|
||||
"isPureShell": true,
|
||||
"isByteCodeShell": true,
|
||||
"platform": "win32",
|
||||
|
BIN
logo.png
BIN
logo.png
Binary file not shown.
Before Width: | Height: | Size: 335 KiB After Width: | Height: | Size: 684 KiB |
@@ -4,16 +4,12 @@
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "4.2.35",
|
||||
"version": "4.2.64",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
"name": "MliKiowa",
|
||||
"link": "https://github.com/MliKiowa"
|
||||
},
|
||||
{
|
||||
"name": "Young",
|
||||
"link": "https://github.com/Wesley-Young"
|
||||
"name": "NapNeko",
|
||||
"link": "https://github.com/NapNeko"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "4.2.35",
|
||||
"version": "4.2.64",
|
||||
"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",
|
||||
@@ -17,6 +17,7 @@
|
||||
"dev:depend": "npm i && cd napcat.webui && npm i"
|
||||
},
|
||||
"devDependencies": {
|
||||
"esbuild": "0.24.0",
|
||||
"@babel/preset-typescript": "^7.24.7",
|
||||
"@eslint/compat": "^1.2.2",
|
||||
"@eslint/eslintrc": "^3.1.0",
|
||||
@@ -36,7 +37,7 @@
|
||||
"@typescript-eslint/parser": "^8.3.0",
|
||||
"ajv": "^8.13.0",
|
||||
"async-mutex": "^0.5.0",
|
||||
"commander": "^12.1.0",
|
||||
"commander": "^13.0.0",
|
||||
"cors": "^2.8.5",
|
||||
"eslint": "^9.14.0",
|
||||
"eslint-import-resolver-typescript": "^3.6.1",
|
||||
@@ -60,4 +61,4 @@
|
||||
"silk-wasm": "^3.6.1",
|
||||
"ws": "^8.18.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -175,10 +175,9 @@ export async function checkUriType(Uri: string) {
|
||||
return { Uri: Uri, Type: FileUriType.Unknown };
|
||||
}
|
||||
|
||||
export async function uriToLocalFile(dir: string, uri: string): Promise<Uri2LocalRes> {
|
||||
export async function uriToLocalFile(dir: string, uri: string, filename: string = randomUUID(), headers?: Record<string, string>): Promise<Uri2LocalRes> {
|
||||
const { Uri: HandledUri, Type: UriType } = await checkUriType(uri);
|
||||
|
||||
const filename = randomUUID();
|
||||
const filePath = path.join(dir, filename);
|
||||
|
||||
switch (UriType) {
|
||||
@@ -191,7 +190,7 @@ export async function uriToLocalFile(dir: string, uri: string): Promise<Uri2Loca
|
||||
}
|
||||
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload(HandledUri);
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers });
|
||||
fs.writeFileSync(filePath, buffer, { flag: 'wx' });
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
}
|
||||
@@ -206,4 +205,4 @@ export async function uriToLocalFile(dir: string, uri: string): Promise<Uri2Loca
|
||||
default:
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
149
src/common/umami.ts
Normal file
149
src/common/umami.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import https from 'node:https';
|
||||
import { napCatVersion } from './version';
|
||||
import os from 'node:os';
|
||||
|
||||
export class UmamiTraceCore {
|
||||
napcatVersion = napCatVersion;
|
||||
qqversion = '1.0.0';
|
||||
guid = 'default-user';
|
||||
heartbeatInterval: NodeJS.Timeout | null = null;
|
||||
website: string = '596cbbb2-1740-4373-a807-cf3d0637bfa7';
|
||||
referrer: string = 'https://trace.napneko.icu/';
|
||||
hostname: string = 'trace.napneko.icu';
|
||||
ua: string = '';
|
||||
workname: string = 'default';
|
||||
bootTime = Date.now();
|
||||
cache: string = '';
|
||||
platform = process.platform;
|
||||
|
||||
init(qqversion: string, guid: string, workname: string) {
|
||||
this.qqversion = qqversion;
|
||||
this.workname = workname;
|
||||
const UaList = {
|
||||
linux: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Ubuntu/11.10 Chromium/27.0.1453.93 Chrome/27.0.1453.93 Safari/537.36',
|
||||
win32: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.2128.93 Safari/537.36',
|
||||
darwin: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36',
|
||||
};
|
||||
|
||||
try {
|
||||
if (this.platform === 'win32') {
|
||||
const ntVersion = os.release();
|
||||
UaList.win32 = `Mozilla/5.0 (Windows NT ${ntVersion}; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.2128.93 Safari/537.36`;
|
||||
} else if (this.platform === 'darwin') {
|
||||
const macVersion = os.release();
|
||||
UaList.darwin = `Mozilla/5.0 (Macintosh; Intel Mac OS X ${macVersion}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36`;
|
||||
}
|
||||
} catch (error) {
|
||||
this.ua = UaList.win32;
|
||||
}
|
||||
|
||||
this.ua = UaList[this.platform as keyof typeof UaList] || UaList.win32;
|
||||
|
||||
this.identifyUser(guid);
|
||||
this.startHeartbeat();
|
||||
}
|
||||
|
||||
identifyUser(guid: string) {
|
||||
this.guid = guid;
|
||||
const data = {
|
||||
napcat_version: this.napcatVersion,
|
||||
qq_version: this.qqversion,
|
||||
napcat_working: this.workname,
|
||||
device_guid: this.guid,
|
||||
device_platform: this.platform,
|
||||
device_arch: os.arch(),
|
||||
boot_time: new Date(this.bootTime + 8 * 60 * 60 * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
||||
sys_time: new Date(Date.now() - os.uptime() * 1000 + 8 * 60 * 60 * 1000).toISOString().replace('T', ' ').substring(0, 19),
|
||||
};
|
||||
this.sendEvent(
|
||||
{
|
||||
website: this.website,
|
||||
hostname: this.hostname,
|
||||
referrer: this.referrer,
|
||||
title: 'NapCat ' + this.napcatVersion,
|
||||
url: `/${this.qqversion}/${this.napcatVersion}/${this.workname}/identify`,
|
||||
},
|
||||
data,
|
||||
'identify'
|
||||
);
|
||||
}
|
||||
|
||||
sendEvent(event: string | object, data?: object, type = 'event') {
|
||||
const env = process.env;
|
||||
const language = env.LANG || env.LANGUAGE || env.LC_ALL || env.LC_MESSAGES;
|
||||
const payload = {
|
||||
...(typeof event === 'string' ? { event } : event),
|
||||
hostname: this.hostname,
|
||||
referrer: this.referrer,
|
||||
website: this.website,
|
||||
language: language || 'en-US',
|
||||
screen: '1920x1080',
|
||||
data: {
|
||||
...data,
|
||||
},
|
||||
};
|
||||
this.sendRequest(payload, type);
|
||||
}
|
||||
|
||||
sendTrace(eventName: string, data: string = '') {
|
||||
const payload = {
|
||||
website: this.website,
|
||||
hostname: this.hostname,
|
||||
title: 'NapCat ' + this.napcatVersion,
|
||||
url: `/${this.qqversion}/${this.napcatVersion}/${this.workname}/${eventName}` + (data ? `/${data}` : ''),
|
||||
referrer: this.referrer,
|
||||
};
|
||||
this.sendRequest(payload);
|
||||
}
|
||||
|
||||
sendRequest(payload: object, type = 'event') {
|
||||
const options = {
|
||||
hostname: '104.19.42.72', // 固定 IP 或者从 hostUrl 获取
|
||||
port: 443,
|
||||
path: '/api/send',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
"Host": "umami.napneko.icu",
|
||||
"Content-Type": "application/json",
|
||||
"User-Agent": this.ua,
|
||||
...(this.cache ? { 'x-umami-cache': this.cache } : {})
|
||||
}
|
||||
};
|
||||
|
||||
const request = https.request(options, (res) => {
|
||||
res.on('error', (error) => {
|
||||
|
||||
});
|
||||
res.on('data', (data) => {
|
||||
if (!this.cache) {
|
||||
this.cache = data.toString();
|
||||
}
|
||||
});
|
||||
}).on('error', () => { });
|
||||
|
||||
request.write(JSON.stringify({ type, payload }));
|
||||
request.end();
|
||||
}
|
||||
|
||||
startHeartbeat() {
|
||||
if (this.heartbeatInterval) {
|
||||
clearInterval(this.heartbeatInterval);
|
||||
}
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
this.sendEvent({
|
||||
name: 'heartbeat',
|
||||
title: 'NapCat ' + this.napcatVersion,
|
||||
url: `/${this.qqversion}/${this.napcatVersion}/${this.workname}/heartbeat`,
|
||||
});
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
stopHeartbeat() {
|
||||
if (this.heartbeatInterval) {
|
||||
clearInterval(this.heartbeatInterval);
|
||||
this.heartbeatInterval = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const UmamiTrace = new UmamiTraceCore();
|
@@ -1 +1 @@
|
||||
export const napCatVersion = '4.2.35';
|
||||
export const napCatVersion = '4.2.64';
|
||||
|
24
src/core/external/appid.json
vendored
24
src/core/external/appid.json
vendored
@@ -134,5 +134,29 @@
|
||||
"3.2.15-30594": {
|
||||
"appid": 537258474,
|
||||
"qua": "V1_LNX_NQ_3.2.15_30594_GW_B"
|
||||
},
|
||||
"9.9.17-30851": {
|
||||
"appid": 537263796,
|
||||
"qua": "V1_WIN_NQ_9.9.17_30851_GW_B"
|
||||
},
|
||||
"3.2.15-30851": {
|
||||
"appid": 537263831,
|
||||
"qua": "V1_LNX_NQ_3.2.15_30851_GW_B"
|
||||
},
|
||||
"6.9.63-30851": {
|
||||
"appid": 537263820,
|
||||
"qua": "V1_MAC_NQ_6.9.63_30851_GW_B"
|
||||
},
|
||||
"9.9.17-30899": {
|
||||
"appid": 537263796,
|
||||
"qua": "V1_WIN_NQ_9.9.17_30899_GW_B"
|
||||
},
|
||||
"3.2.15-30899": {
|
||||
"appid": 537263831,
|
||||
"qua": "V1_LNX_NQ_3.2.15_30899_GW_B"
|
||||
},
|
||||
"6.9.63-30899": {
|
||||
"appid": 537263820,
|
||||
"qua": "V1_MAC_NQ_6.9.63_30899_GW_B"
|
||||
}
|
||||
}
|
40
src/core/external/offset.json
vendored
40
src/core/external/offset.json
vendored
@@ -162,5 +162,45 @@
|
||||
"3.2.15-30594-arm64": {
|
||||
"send": "70C40E8",
|
||||
"recv": "70C7920"
|
||||
},
|
||||
"9.9.17-30851-x64": {
|
||||
"send": "395C150",
|
||||
"recv": "3960584"
|
||||
},
|
||||
"3.2.15-30851-x64": {
|
||||
"send": "A4A03E0",
|
||||
"recv": "A4A3CE0"
|
||||
},
|
||||
"3.2.15-30851-arm64": {
|
||||
"send": "713A318",
|
||||
"recv": "713DB50"
|
||||
},
|
||||
"6.9.63.30851-x64": {
|
||||
"send": "46C8040",
|
||||
"recv": "46CA8AC"
|
||||
},
|
||||
"6.9.63-30851-arm64": {
|
||||
"send": "41DCBD8",
|
||||
"recv": "41DF3F0"
|
||||
},
|
||||
"9.9.17-30899-x64": {
|
||||
"send": "395C150",
|
||||
"recv": "3960584"
|
||||
},
|
||||
"3.2.15-30899-x64": {
|
||||
"send": "A4A03E0",
|
||||
"recv": "A4A3CE0"
|
||||
},
|
||||
"3.2.15-30899-arm64": {
|
||||
"send": "713A318",
|
||||
"recv": "713DB50"
|
||||
},
|
||||
"6.9.63.30899-x64": {
|
||||
"send": "46C8040",
|
||||
"recv": "46CA8AC"
|
||||
},
|
||||
"6.9.63-30899-arm64": {
|
||||
"send": "41DCBD8",
|
||||
"recv": "41DF3F0"
|
||||
}
|
||||
}
|
@@ -1,49 +0,0 @@
|
||||
// TODO: further refactor in NapCat.Packet v2
|
||||
import { NapProtoMsg, ProtoField, ScalarType } from "@napneko/nap-proto-core";
|
||||
|
||||
const BodyInner = {
|
||||
msgType: ProtoField(1, ScalarType.UINT32, true),
|
||||
subType: ProtoField(2, ScalarType.UINT32, true)
|
||||
};
|
||||
|
||||
const NoifyData = {
|
||||
skip: ProtoField(1, ScalarType.BYTES, true),
|
||||
innerData: ProtoField(2, ScalarType.BYTES, true)
|
||||
};
|
||||
|
||||
const MsgHead = {
|
||||
bodyInner: ProtoField(2, () => BodyInner, true),
|
||||
noifyData: ProtoField(3, () => NoifyData, true)
|
||||
};
|
||||
|
||||
const Message = {
|
||||
msgHead: ProtoField(1, () => MsgHead)
|
||||
};
|
||||
|
||||
const SubDetail = {
|
||||
msgSeq: ProtoField(1, ScalarType.UINT32),
|
||||
msgTime: ProtoField(2, ScalarType.UINT32),
|
||||
senderUid: ProtoField(6, ScalarType.STRING)
|
||||
};
|
||||
|
||||
const RecallDetails = {
|
||||
operatorUid: ProtoField(1, ScalarType.STRING),
|
||||
subDetail: ProtoField(3, () => SubDetail)
|
||||
};
|
||||
|
||||
const RecallGroup = {
|
||||
type: ProtoField(1, ScalarType.INT32),
|
||||
peerUid: ProtoField(4, ScalarType.UINT32),
|
||||
recallDetails: ProtoField(11, () => RecallDetails),
|
||||
grayTipsSeq: ProtoField(37, ScalarType.UINT32)
|
||||
};
|
||||
|
||||
export function decodeMessage(buffer: Uint8Array) {
|
||||
const msg = new NapProtoMsg(Message);
|
||||
return msg.decode(buffer);
|
||||
}
|
||||
|
||||
export function decodeRecallGroup(buffer: Uint8Array){
|
||||
const msg = new NapProtoMsg(RecallGroup);
|
||||
return msg.decode(buffer);
|
||||
}
|
138
src/core/helper/status.ts
Normal file
138
src/core/helper/status.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import os from "node:os";
|
||||
import EventEmitter from "node:events";
|
||||
|
||||
export interface SystemStatus {
|
||||
cpu: {
|
||||
model: string,
|
||||
speed: string
|
||||
usage: {
|
||||
system: string
|
||||
qq: string
|
||||
},
|
||||
core: number
|
||||
},
|
||||
memory: {
|
||||
total: string
|
||||
usage: {
|
||||
system: string
|
||||
qq: string
|
||||
}
|
||||
},
|
||||
arch: string
|
||||
}
|
||||
|
||||
export class StatusHelper {
|
||||
private psCpuUsage = process.cpuUsage();
|
||||
private psCurrentTime = process.hrtime();
|
||||
private cpuTimes = os.cpus().map(cpu => cpu.times);
|
||||
|
||||
private replaceNaN(value: number) {
|
||||
return isNaN(value) ? 0 : value;
|
||||
}
|
||||
|
||||
private sysCpuInfo() {
|
||||
const currentTimes = os.cpus().map(cpu => cpu.times);
|
||||
const { total, active } = currentTimes.map((times, index) => {
|
||||
const prevTimes = this.cpuTimes[index];
|
||||
const totalCurrent = times.user + times.nice + times.sys + times.idle + times.irq;
|
||||
const totalPrev = prevTimes.user + prevTimes.nice + prevTimes.sys + prevTimes.idle + prevTimes.irq;
|
||||
const activeCurrent = totalCurrent - times.idle;
|
||||
const activePrev = totalPrev - prevTimes.idle;
|
||||
return {
|
||||
total: totalCurrent - totalPrev,
|
||||
active: activeCurrent - activePrev
|
||||
};
|
||||
}).reduce((acc, cur) => ({
|
||||
total: acc.total + cur.total,
|
||||
active: acc.active + cur.active
|
||||
}), { total: 0, active: 0 });
|
||||
this.cpuTimes = currentTimes;
|
||||
return {
|
||||
usage: this.replaceNaN(((active / total) * 100)).toFixed(2),
|
||||
model: os.cpus()[0].model,
|
||||
speed: os.cpus()[0].speed,
|
||||
core: os.cpus().length
|
||||
};
|
||||
}
|
||||
|
||||
private sysMemoryUsage() {
|
||||
const { total, free } = { total: os.totalmem(), free: os.freemem() };
|
||||
return ((total - free) / 1024 / 1024).toFixed(2);
|
||||
}
|
||||
|
||||
private qqUsage() {
|
||||
const mem = process.memoryUsage();
|
||||
const numCpus = os.cpus().length;
|
||||
const usageDiff = process.cpuUsage(this.psCpuUsage);
|
||||
const endTime = process.hrtime(this.psCurrentTime);
|
||||
this.psCpuUsage = process.cpuUsage();
|
||||
this.psCurrentTime = process.hrtime();
|
||||
const usageMS = (usageDiff.user + usageDiff.system) / 1e3;
|
||||
const totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
|
||||
const normPercent = (usageMS / totalMS / numCpus) * 100;
|
||||
return {
|
||||
cpu: this.replaceNaN(normPercent).toFixed(2),
|
||||
memory: ((mem.heapTotal + mem.external + mem.arrayBuffers) / 1024 / 1024).toFixed(2)
|
||||
};
|
||||
}
|
||||
|
||||
systemStatus(): SystemStatus {
|
||||
const qqUsage = this.qqUsage();
|
||||
const sysCpuInfo = this.sysCpuInfo();
|
||||
return {
|
||||
cpu: {
|
||||
core: sysCpuInfo.core,
|
||||
model: sysCpuInfo.model,
|
||||
speed: (sysCpuInfo.speed / 1000).toFixed(2),
|
||||
usage: {
|
||||
system: sysCpuInfo.usage,
|
||||
qq: qqUsage.cpu
|
||||
},
|
||||
},
|
||||
memory: {
|
||||
total: (os.totalmem() / 1024 / 1024).toFixed(2),
|
||||
usage: {
|
||||
system: this.sysMemoryUsage(),
|
||||
qq: qqUsage.memory
|
||||
}
|
||||
},
|
||||
arch: `${os.platform()} ${os.arch()} ${os.release()}`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class StatusHelperSubscription extends EventEmitter {
|
||||
private statusHelper: StatusHelper;
|
||||
private interval: NodeJS.Timeout | null = null;
|
||||
|
||||
constructor(time: number = 3000) {
|
||||
super();
|
||||
this.statusHelper = new StatusHelper();
|
||||
this.on('newListener', (event: string) => {
|
||||
if (event === 'statusUpdate' && this.listenerCount('statusUpdate') === 0) {
|
||||
this.startInterval(time);
|
||||
}
|
||||
});
|
||||
this.on('removeListener', (event: string) => {
|
||||
if (event === 'statusUpdate' && this.listenerCount('statusUpdate') === 0) {
|
||||
this.stopInterval();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private startInterval(time: number) {
|
||||
this.interval ??= setInterval(() => {
|
||||
const status = this.statusHelper.systemStatus();
|
||||
this.emit('statusUpdate', status);
|
||||
}, time);
|
||||
}
|
||||
|
||||
private stopInterval() {
|
||||
if (this.interval) {
|
||||
clearInterval(this.interval);
|
||||
this.interval = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const statusHelperSubscription = new StatusHelperSubscription();
|
@@ -30,6 +30,7 @@ import os from 'node:os';
|
||||
import { NodeIKernelMsgListener, NodeIKernelProfileListener } from '@/core/listeners';
|
||||
import { proxiedListenerOf } from '@/common/proxy-handler';
|
||||
import { NTQQPacketApi } from './apis/packet';
|
||||
import { UmamiTrace } from '@/common/umami';
|
||||
export * from './wrapper';
|
||||
export * from './types';
|
||||
export * from './services';
|
||||
@@ -152,7 +153,13 @@ export class NapCatCore {
|
||||
// Renamed from 'InitDataListener'
|
||||
async initNapCatCoreListeners() {
|
||||
const msgListener = new NodeIKernelMsgListener();
|
||||
|
||||
msgListener.onKickedOffLine = (Info: KickedOffLineInfo) => {
|
||||
if (this.context.workingEnv === NapCatCoreWorkingEnv.Framework) {
|
||||
UmamiTrace.sendTrace('event/kickoff');
|
||||
} else {
|
||||
UmamiTrace.sendTrace('event/kickoff');
|
||||
}
|
||||
// 下线通知
|
||||
this.context.logger.logError('[KickedOffLine] [' + Info.tipsTitle + '] ' + Info.tipsDesc);
|
||||
this.selfInfo.online = false;
|
||||
|
@@ -23,7 +23,9 @@ export class PacketClientSession {
|
||||
get operation() {
|
||||
return this.context.operation;
|
||||
}
|
||||
|
||||
get client() {
|
||||
return this.context.client;
|
||||
}
|
||||
// TODO: global message element adapter (?
|
||||
get msgConverter() {
|
||||
return this.context.msgConverter;
|
||||
|
@@ -21,7 +21,7 @@ export class PacketOperationContext {
|
||||
}
|
||||
|
||||
async GroupPoke(groupUin: number, uin: number) {
|
||||
const req = trans.SendPoke.build(groupUin, uin);
|
||||
const req = trans.SendPoke.build(uin, groupUin);
|
||||
await this.context.client.sendOidbPacket(req);
|
||||
}
|
||||
|
||||
|
@@ -72,6 +72,14 @@ export const GroupChange = {
|
||||
field7: ProtoField(7, ScalarType.BYTES, true),
|
||||
};
|
||||
|
||||
export const GroupInvite = {
|
||||
groupUin: ProtoField(1, ScalarType.UINT32),
|
||||
field2: ProtoField(2, ScalarType.UINT32),
|
||||
field3: ProtoField(2, ScalarType.UINT32),
|
||||
field4: ProtoField(2, ScalarType.UINT32),
|
||||
invitorUid: ProtoField(5, ScalarType.STRING),
|
||||
};
|
||||
|
||||
export const PushMsgBody = {
|
||||
responseHead: ProtoField(1, () => ResponseHead),
|
||||
contentHead: ProtoField(2, () => ContentHead),
|
||||
|
@@ -56,6 +56,7 @@ export interface GrayTipElement {
|
||||
aioOpGrayTipElement: TipAioOpGrayTipElement;
|
||||
groupElement: TipGroupElement;
|
||||
xmlElement: {
|
||||
busiId: string;
|
||||
content: string;
|
||||
templId: string;
|
||||
};
|
||||
|
@@ -9,4 +9,5 @@ export * from './sign';
|
||||
export * from './element';
|
||||
export * from './constant';
|
||||
export * from './graytip';
|
||||
export * from './emoji';
|
||||
export * from './emoji';
|
||||
export * from './service';
|
@@ -508,7 +508,7 @@ export interface RawMessage {
|
||||
*/
|
||||
export interface QueryMsgsParams {
|
||||
chatInfo: Peer;
|
||||
filterMsgType: [];
|
||||
filterMsgType: Array<{ type: NTMsgType, subType: Array<number> }>;
|
||||
filterSendersUid: string[];
|
||||
filterMsgFromTime: string;
|
||||
filterMsgToTime: string;
|
||||
|
35
src/core/types/service.ts
Normal file
35
src/core/types/service.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
export enum LoginErrorCode {
|
||||
KLOGINERRORACCOUNTNOTUIN = 140022018,
|
||||
KLOGINERRORACCOUNTORPASSWORDERROR = 140022013,
|
||||
KLOGINERRORBLACKACCOUNT = 150022021,
|
||||
KLOGINERRORDEFAULT = 140022000,
|
||||
KLOGINERROREXPIRETICKET = 140022014,
|
||||
KLOGINERRORFROZEN = 140022005,
|
||||
KLOGINERRORILLAGETICKET = 140022016,
|
||||
KLOGINERRORINVAILDCOOKIE = 140022012,
|
||||
KLOGINERRORINVALIDPARAMETER = 140022001,
|
||||
KLOGINERRORKICKEDTICKET = 140022015,
|
||||
KLOGINERRORMUTIPLEPASSWORDINCORRECT = 150022029,
|
||||
KLOGINERRORNEEDUPDATE = 140022004,
|
||||
KLOGINERRORNEEDVERIFYREALNAME = 140022019,
|
||||
KLOGINERRORNEWDEVICE = 140022010,
|
||||
KLOGINERRORNICEACCOUNTEXPIRED = 150022020,
|
||||
KLOGINERRORNICEACCOUNTPARENTCHILDEXPIRED = 150022025,
|
||||
KLOGINERRORPASSWORD = 2,
|
||||
KLOGINERRORPROOFWATER = 140022008,
|
||||
KLOGINERRORPROTECT = 140022006,
|
||||
KLOGINERRORREFUSEPASSOWRDLOGIN = 140022009,
|
||||
KLOGINERRORREMINDCANAELLATEDSTATUS = 150022028,
|
||||
KLOGINERRORSCAN = 1,
|
||||
KLOGINERRORSCCESS = 0,
|
||||
KLOGINERRORSECBEAT = 140022017,
|
||||
KLOGINERRORSMSINVALID = 150022026,
|
||||
KLOGINERRORSTRICK = 140022007,
|
||||
KLOGINERRORSYSTEMFAILED = 140022002,
|
||||
KLOGINERRORTGTGTEXCHAGEA1FORBID = 150022027,
|
||||
KLOGINERRORTIMEOUTRETRY = 140022003,
|
||||
KLOGINERRORTOOMANYTIMESTODAY = 150022023,
|
||||
KLOGINERRORTOOOFTEN = 150022022,
|
||||
KLOGINERRORUNREGISTERED = 150022024,
|
||||
KLOGINERRORUNUSUALDEVICE = 140022011,
|
||||
}
|
@@ -9,6 +9,7 @@ import { NodeIKernelLoginService } from '@/core/services';
|
||||
import { NodeIQQNTWrapperSession, WrapperNodeApi } from '@/core/wrapper';
|
||||
import { InitWebUi, WebUiConfig } from '@/webui';
|
||||
import { NapCatOneBot11Adapter } from '@/onebot';
|
||||
import { UmamiTrace } from '@/common/umami';
|
||||
|
||||
//Framework ES入口文件
|
||||
export async function getWebUiUrl() {
|
||||
@@ -25,8 +26,10 @@ export async function NCoreInitFramework(
|
||||
console.log('NapCat Framework App Loading...');
|
||||
|
||||
process.on('uncaughtException', (err) => {
|
||||
UmamiTrace.sendTrace('uncaught/error', err.message);
|
||||
console.log('[NapCat] [Error] Unhandled Exception:', err.message);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.log('[NapCat] [Error] unhandledRejection:', reason);
|
||||
});
|
||||
@@ -35,6 +38,10 @@ export async function NCoreInitFramework(
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
|
||||
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
|
||||
let guid = loginService.getMachineGuid();
|
||||
UmamiTrace.init(basicInfoWrapper.getFullQQVesion(), guid,'framework');
|
||||
UmamiTrace.sendTrace('boot/init');
|
||||
UmamiTrace.sendTrace('login/success');
|
||||
//直到登录成功后,执行下一步
|
||||
const selfInfo = await new Promise<SelfInfo>((resolveSelfInfo) => {
|
||||
const loginListener = new NodeIKernelLoginListener();
|
||||
|
14
src/onebot/action/extends/GetClientkey.ts
Normal file
14
src/onebot/action/extends/GetClientkey.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ActionName } from '@/onebot/action/router';
|
||||
import { OneBotAction } from '../OneBotAction';
|
||||
|
||||
interface GetClientkeyResponse {
|
||||
clientkey?: string;
|
||||
}
|
||||
|
||||
export class GetClientkey extends OneBotAction<void, GetClientkeyResponse> {
|
||||
actionName = ActionName.GetClientkey;
|
||||
|
||||
async _handle() {
|
||||
return { clientkey: (await this.core.apis.UserApi.forceFetchClientKey()).clientKey };
|
||||
}
|
||||
}
|
21
src/onebot/action/extends/SendPacket.ts
Normal file
21
src/onebot/action/extends/SendPacket.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { GetPacketStatusDepends } from '@/onebot/action/packet/GetPacketStatus';
|
||||
import { ActionName } from '@/onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
const SchemaData = Type.Object({
|
||||
cmd: Type.String(),
|
||||
data: Type.String(),
|
||||
rsp: Type.Union([Type.String(), Type.Boolean()], { default: true }),
|
||||
});
|
||||
|
||||
type Payload = Static<typeof SchemaData>;
|
||||
|
||||
export class SendPacket extends GetPacketStatusDepends<Payload, any> {
|
||||
payloadSchema = SchemaData;
|
||||
actionName = ActionName.SendPacket;
|
||||
async _handle(payload: Payload) {
|
||||
const rsp = typeof payload.rsp === 'boolean' ? payload.rsp : payload.rsp === 'true';
|
||||
const data = await this.core.apis.PacketApi.pkt.client.sendOidbPacket({ cmd: payload.cmd, data: payload.data as any }, rsp);
|
||||
return typeof data === 'object' ? data.toString('hex') : undefined;
|
||||
}
|
||||
}
|
@@ -17,7 +17,7 @@ class SetGroupSignBase extends GetPacketStatusDepends<Payload, any> {
|
||||
}
|
||||
|
||||
export class SetGroupSign extends SetGroupSignBase {
|
||||
actionName = ActionName.SendGroupSign;
|
||||
actionName = ActionName.SetGroupSign;
|
||||
}
|
||||
|
||||
export class SendGroupSign extends SetGroupSignBase {
|
||||
|
@@ -2,7 +2,7 @@ import { OneBotAction } from '@/onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/onebot/action/router';
|
||||
import fs from 'fs';
|
||||
import { join as joinPath } from 'node:path';
|
||||
import { calculateFileMD5, httpDownload } from '@/common/file';
|
||||
import { calculateFileMD5, uriToLocalFile } from '@/common/file';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
@@ -26,17 +26,20 @@ export default class GoCQHTTPDownloadFile extends OneBotAction<Payload, FileResp
|
||||
async _handle(payload: Payload): Promise<FileResponse> {
|
||||
const isRandomName = !payload.name;
|
||||
const name = payload.name || randomUUID();
|
||||
const filePath = joinPath(this.core.NapCatTempPath, name);
|
||||
let result: Awaited<ReturnType<typeof uriToLocalFile>>;
|
||||
|
||||
if (payload.base64) {
|
||||
fs.writeFileSync(filePath, payload.base64, 'base64');
|
||||
result = await uriToLocalFile(this.core.NapCatTempPath, `base64://${payload.base64}`, name);
|
||||
} else if (payload.url) {
|
||||
const headers = this.getHeaders(payload.headers);
|
||||
const buffer = await httpDownload({ url: payload.url, headers: headers });
|
||||
fs.writeFileSync(filePath, Buffer.from(buffer), 'binary');
|
||||
result = await uriToLocalFile(this.core.NapCatTempPath, payload.url, name, headers);
|
||||
} else {
|
||||
throw new Error('不存在任何文件, 无法下载');
|
||||
}
|
||||
if (!result.success) {
|
||||
throw new Error(result.errMsg);
|
||||
}
|
||||
const filePath = result.path;
|
||||
if (fs.existsSync(filePath)) {
|
||||
|
||||
if (isRandomName) {
|
||||
|
@@ -14,6 +14,6 @@ export class GroupPoke extends GetPacketStatusDepends<Payload, any> {
|
||||
payloadSchema = SchemaData;
|
||||
|
||||
async _handle(payload: Payload) {
|
||||
await this.core.apis.PacketApi.pkt.operation.GroupPoke(+payload.user_id, +payload.group_id);
|
||||
await this.core.apis.PacketApi.pkt.operation.GroupPoke(+payload.group_id, +payload.user_id);
|
||||
}
|
||||
}
|
||||
|
@@ -19,12 +19,11 @@ export default class SetGroupAddRequest extends OneBotAction<Payload, null> {
|
||||
const flag = payload.flag.toString();
|
||||
const approve = payload.approve?.toString() !== 'false';
|
||||
const reason = payload.reason ?? ' ';
|
||||
|
||||
const notify = await this.findNotify(flag);
|
||||
let invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(flag);
|
||||
const notify = invite_notify ?? await this.findNotify(flag);
|
||||
if (!notify) {
|
||||
throw new Error('No such request');
|
||||
}
|
||||
|
||||
await this.core.apis.GroupApi.handleGroupRequest(
|
||||
notify,
|
||||
approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
|
||||
|
@@ -102,6 +102,9 @@ import { SendGroupAiRecord } from "@/onebot/action/group/SendGroupAiRecord";
|
||||
import { GetAiCharacters } from "@/onebot/action/extends/GetAiCharacters";
|
||||
import { GetGuildList } from './guild/GetGuildList';
|
||||
import { GetGuildProfile } from './guild/GetGuildProfile';
|
||||
import { GetClientkey } from './extends/GetClientkey';
|
||||
import { SendPacket } from './extends/SendPacket';
|
||||
import { SendPoke } from "@/onebot/action/packet/SendPoke";
|
||||
|
||||
export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
|
||||
|
||||
@@ -123,6 +126,7 @@ export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetGroupRootFiles(obContext, core),
|
||||
new SetGroupSign(obContext, core),
|
||||
new SendGroupSign(obContext, core),
|
||||
new GetClientkey(obContext, core),
|
||||
// onebot11
|
||||
new SendLike(obContext, core),
|
||||
new GetMsg(obContext, core),
|
||||
@@ -216,6 +220,8 @@ export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetAiRecord(obContext, core),
|
||||
new SendGroupAiRecord(obContext, core),
|
||||
new GetAiCharacters(obContext, core),
|
||||
new SendPacket(obContext, core),
|
||||
new SendPoke(obContext, core),
|
||||
];
|
||||
|
||||
type HandlerUnion = typeof actionHandlers[number];
|
||||
|
23
src/onebot/action/packet/SendPoke.ts
Normal file
23
src/onebot/action/packet/SendPoke.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { ActionName } from '@/onebot/action/router';
|
||||
import { GetPacketStatusDepends } from "@/onebot/action/packet/GetPacketStatus";
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
const SchemaData = Type.Object({
|
||||
group_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
|
||||
user_id: Type.Union([Type.Number(), Type.String()]),
|
||||
});
|
||||
|
||||
type Payload = Static<typeof SchemaData>;
|
||||
|
||||
export class SendPoke extends GetPacketStatusDepends<Payload, any> {
|
||||
actionName = ActionName.SendPoke;
|
||||
payloadSchema = SchemaData;
|
||||
|
||||
async _handle(payload: Payload) {
|
||||
if (payload.group_id) {
|
||||
await this.core.apis.PacketApi.pkt.operation.GroupPoke(+payload.group_id, +payload.user_id);
|
||||
} else {
|
||||
await this.core.apis.PacketApi.pkt.operation.FriendPoke(+payload.user_id);
|
||||
}
|
||||
}
|
||||
}
|
@@ -13,134 +13,138 @@ export interface InvalidCheckResult {
|
||||
[k: string | number]: any;
|
||||
}
|
||||
|
||||
export const ActionName = {
|
||||
export const ActionName = {
|
||||
// onebot 11
|
||||
SendPrivateMsg : 'send_private_msg',
|
||||
SendGroupMsg : 'send_group_msg',
|
||||
SendMsg : 'send_msg',
|
||||
DeleteMsg : 'delete_msg',
|
||||
GetMsg : 'get_msg',
|
||||
GoCQHTTP_GetForwardMsg : 'get_forward_msg',
|
||||
SendLike : 'send_like',
|
||||
SetGroupKick : 'set_group_kick',
|
||||
SetGroupBan : 'set_group_ban',
|
||||
SendPrivateMsg: 'send_private_msg',
|
||||
SendGroupMsg: 'send_group_msg',
|
||||
SendMsg: 'send_msg',
|
||||
DeleteMsg: 'delete_msg',
|
||||
GetMsg: 'get_msg',
|
||||
GoCQHTTP_GetForwardMsg: 'get_forward_msg',
|
||||
SendLike: 'send_like',
|
||||
SetGroupKick: 'set_group_kick',
|
||||
SetGroupBan: 'set_group_ban',
|
||||
// SetGroupAnoymousBan : 'set_group_anonymous_ban',
|
||||
SetGroupWholeBan : 'set_group_whole_ban',
|
||||
SetGroupAdmin : 'set_group_admin',
|
||||
SetGroupWholeBan: 'set_group_whole_ban',
|
||||
SetGroupAdmin: 'set_group_admin',
|
||||
// SetGroupAnoymous : 'set_group_anonymous',
|
||||
SetGroupCard : 'set_group_card',
|
||||
SetGroupName : 'set_group_name',
|
||||
SetGroupLeave : 'set_group_leave',
|
||||
SetSpecialTittle : 'set_group_special_title',
|
||||
SetFriendAddRequest : 'set_friend_add_request',
|
||||
SetGroupAddRequest : 'set_group_add_request',
|
||||
GetLoginInfo : 'get_login_info',
|
||||
GoCQHTTP_GetStrangerInfo : 'get_stranger_info',
|
||||
GetFriendList : 'get_friend_list',
|
||||
GetGroupInfo : 'get_group_info',
|
||||
GetGroupList : 'get_group_list',
|
||||
GetGroupMemberInfo : 'get_group_member_info',
|
||||
GetGroupMemberList : 'get_group_member_list',
|
||||
GetGroupHonorInfo : 'get_group_honor_info',
|
||||
GetCookies : 'get_cookies',
|
||||
GetCSRF : 'get_csrf_token',
|
||||
GetCredentials : 'get_credentials',
|
||||
GetRecord : 'get_record',
|
||||
GetImage : 'get_image',
|
||||
CanSendImage : 'can_send_image',
|
||||
CanSendRecord : 'can_send_record',
|
||||
GetStatus : 'get_status',
|
||||
GetVersionInfo : 'get_version_info',
|
||||
SetGroupCard: 'set_group_card',
|
||||
SetGroupName: 'set_group_name',
|
||||
SetGroupLeave: 'set_group_leave',
|
||||
SetSpecialTittle: 'set_group_special_title',
|
||||
SetFriendAddRequest: 'set_friend_add_request',
|
||||
SetGroupAddRequest: 'set_group_add_request',
|
||||
GetLoginInfo: 'get_login_info',
|
||||
GoCQHTTP_GetStrangerInfo: 'get_stranger_info',
|
||||
GetFriendList: 'get_friend_list',
|
||||
GetGroupInfo: 'get_group_info',
|
||||
GetGroupList: 'get_group_list',
|
||||
GetGroupMemberInfo: 'get_group_member_info',
|
||||
GetGroupMemberList: 'get_group_member_list',
|
||||
GetGroupHonorInfo: 'get_group_honor_info',
|
||||
GetCookies: 'get_cookies',
|
||||
GetCSRF: 'get_csrf_token',
|
||||
GetCredentials: 'get_credentials',
|
||||
GetRecord: 'get_record',
|
||||
GetImage: 'get_image',
|
||||
CanSendImage: 'can_send_image',
|
||||
CanSendRecord: 'can_send_record',
|
||||
GetStatus: 'get_status',
|
||||
GetVersionInfo: 'get_version_info',
|
||||
// Reboot : 'set_restart',
|
||||
// CleanCache : 'clean_cache',
|
||||
|
||||
// go-cqhttp
|
||||
SetQQProfile : 'set_qq_profile',
|
||||
SetQQProfile: 'set_qq_profile',
|
||||
// QidianGetAccountInfo : 'qidian_get_account_info',
|
||||
GoCQHTTP_GetModelShow : '_get_model_show',
|
||||
GoCQHTTP_SetModelShow : '_set_model_show',
|
||||
GetOnlineClient : 'get_online_clients',
|
||||
GoCQHTTP_GetModelShow: '_get_model_show',
|
||||
GoCQHTTP_SetModelShow: '_set_model_show',
|
||||
GetOnlineClient: 'get_online_clients',
|
||||
// GetUnidirectionalFriendList : 'get_unidirectional_friend_list',
|
||||
GoCQHTTP_DeleteFriend : 'delete_friend',
|
||||
GoCQHTTP_DeleteFriend: 'delete_friend',
|
||||
// DeleteUnidirectionalFriendList : 'delete_unidirectional_friend',
|
||||
GoCQHTTP_MarkMsgAsRead : 'mark_msg_as_read',
|
||||
GoCQHTTP_SendGroupForwardMsg : 'send_group_forward_msg',
|
||||
GoCQHTTP_SendPrivateForwardMsg : 'send_private_forward_msg',
|
||||
GoCQHTTP_GetGroupMsgHistory : 'get_group_msg_history',
|
||||
OCRImage : 'ocr_image',
|
||||
IOCRImage : '.ocr_image',
|
||||
GetGroupSystemMsg : 'get_group_system_msg',
|
||||
GoCQHTTP_GetEssenceMsg : 'get_essence_msg_list',
|
||||
GoCQHTTP_GetGroupAtAllRemain : 'get_group_at_all_remain',
|
||||
SetGroupPortrait : 'set_group_portrait',
|
||||
SetEssenceMsg : 'set_essence_msg',
|
||||
DelEssenceMsg : 'delete_essence_msg',
|
||||
GoCQHTTP_SendGroupNotice : '_send_group_notice',
|
||||
GoCQHTTP_GetGroupNotice : '_get_group_notice',
|
||||
GoCQHTTP_UploadGroupFile : 'upload_group_file',
|
||||
GOCQHTTP_DeleteGroupFile : 'delete_group_file',
|
||||
GoCQHTTP_CreateGroupFileFolder : 'create_group_file_folder',
|
||||
GoCQHTTP_DeleteGroupFileFolder : 'delete_group_folder',
|
||||
GoCQHTTP_GetGroupFileSystemInfo : 'get_group_file_system_info',
|
||||
GoCQHTTP_GetGroupRootFiles : 'get_group_root_files',
|
||||
GoCQHTTP_GetGroupFilesByFolder : 'get_group_files_by_folder',
|
||||
GOCQHTTP_GetGroupFileUrl : 'get_group_file_url',
|
||||
GOCQHTTP_UploadPrivateFile : 'upload_private_file',
|
||||
GoCQHTTP_MarkMsgAsRead: 'mark_msg_as_read',
|
||||
GoCQHTTP_SendGroupForwardMsg: 'send_group_forward_msg',
|
||||
GoCQHTTP_SendPrivateForwardMsg: 'send_private_forward_msg',
|
||||
GoCQHTTP_GetGroupMsgHistory: 'get_group_msg_history',
|
||||
OCRImage: 'ocr_image',
|
||||
IOCRImage: '.ocr_image',
|
||||
GetGroupSystemMsg: 'get_group_system_msg',
|
||||
GoCQHTTP_GetEssenceMsg: 'get_essence_msg_list',
|
||||
GoCQHTTP_GetGroupAtAllRemain: 'get_group_at_all_remain',
|
||||
SetGroupPortrait: 'set_group_portrait',
|
||||
SetEssenceMsg: 'set_essence_msg',
|
||||
DelEssenceMsg: 'delete_essence_msg',
|
||||
GoCQHTTP_SendGroupNotice: '_send_group_notice',
|
||||
GoCQHTTP_GetGroupNotice: '_get_group_notice',
|
||||
GoCQHTTP_UploadGroupFile: 'upload_group_file',
|
||||
GOCQHTTP_DeleteGroupFile: 'delete_group_file',
|
||||
GoCQHTTP_CreateGroupFileFolder: 'create_group_file_folder',
|
||||
GoCQHTTP_DeleteGroupFileFolder: 'delete_group_folder',
|
||||
GoCQHTTP_GetGroupFileSystemInfo: 'get_group_file_system_info',
|
||||
GoCQHTTP_GetGroupRootFiles: 'get_group_root_files',
|
||||
GoCQHTTP_GetGroupFilesByFolder: 'get_group_files_by_folder',
|
||||
GOCQHTTP_GetGroupFileUrl: 'get_group_file_url',
|
||||
GOCQHTTP_UploadPrivateFile: 'upload_private_file',
|
||||
// GOCQHTTP_ReloadEventFilter : 'reload_event_filter',
|
||||
GoCQHTTP_DownloadFile : 'download_file',
|
||||
GoCQHTTP_CheckUrlSafely : 'check_url_safely',
|
||||
GoCQHTTP_GetWordSlices : '.get_word_slices',
|
||||
GoCQHTTP_HandleQuickAction : '.handle_quick_operation',
|
||||
GoCQHTTP_DownloadFile: 'download_file',
|
||||
GoCQHTTP_CheckUrlSafely: 'check_url_safely',
|
||||
GoCQHTTP_GetWordSlices: '.get_word_slices',
|
||||
GoCQHTTP_HandleQuickAction: '.handle_quick_operation',
|
||||
|
||||
// 以下为扩展napcat扩展
|
||||
Unknown : 'unknown',
|
||||
SharePeer : 'ArkSharePeer',
|
||||
ShareGroupEx : 'ArkShareGroup',
|
||||
Unknown: 'unknown',
|
||||
SharePeer: 'ArkSharePeer',
|
||||
ShareGroupEx: 'ArkShareGroup',
|
||||
// RebootNormal : 'reboot_normal', //无快速登录重新启动
|
||||
GetRobotUinRange : 'get_robot_uin_range',
|
||||
SetOnlineStatus : 'set_online_status',
|
||||
GetFriendsWithCategory : 'get_friends_with_category',
|
||||
SetQQAvatar : 'set_qq_avatar',
|
||||
GetFile : 'get_file',
|
||||
ForwardFriendSingleMsg : 'forward_friend_single_msg',
|
||||
ForwardGroupSingleMsg : 'forward_group_single_msg',
|
||||
TranslateEnWordToZn : 'translate_en2zh',
|
||||
SetMsgEmojiLike : 'set_msg_emoji_like',
|
||||
GoCQHTTP_SendForwardMsg : 'send_forward_msg',
|
||||
MarkPrivateMsgAsRead : 'mark_private_msg_as_read',
|
||||
MarkGroupMsgAsRead : 'mark_group_msg_as_read',
|
||||
GetFriendMsgHistory : 'get_friend_msg_history',
|
||||
CreateCollection : 'create_collection',
|
||||
GetCollectionList : 'get_collection_list',
|
||||
SetLongNick : 'set_self_longnick',
|
||||
GetRecentContact : 'get_recent_contact',
|
||||
_MarkAllMsgAsRead : '_mark_all_as_read',
|
||||
GetProfileLike : 'get_profile_like',
|
||||
FetchCustomFace : 'fetch_custom_face',
|
||||
FetchEmojiLike : 'fetch_emoji_like',
|
||||
SetInputStatus : 'set_input_status',
|
||||
GetGroupInfoEx : 'get_group_info_ex',
|
||||
GetGroupIgnoreAddRequest : 'get_group_ignore_add_request',
|
||||
DelGroupNotice : '_del_group_notice',
|
||||
FetchUserProfileLike : 'fetch_user_profile_like',
|
||||
FriendPoke : 'friend_poke',
|
||||
GroupPoke : 'group_poke',
|
||||
GetPacketStatus : 'nc_get_packet_status',
|
||||
GetUserStatus : 'nc_get_user_status',
|
||||
GetRkey : 'nc_get_rkey',
|
||||
GetGroupShutList : 'get_group_shut_list',
|
||||
GetRobotUinRange: 'get_robot_uin_range',
|
||||
SetOnlineStatus: 'set_online_status',
|
||||
GetFriendsWithCategory: 'get_friends_with_category',
|
||||
SetQQAvatar: 'set_qq_avatar',
|
||||
GetFile: 'get_file',
|
||||
ForwardFriendSingleMsg: 'forward_friend_single_msg',
|
||||
ForwardGroupSingleMsg: 'forward_group_single_msg',
|
||||
TranslateEnWordToZn: 'translate_en2zh',
|
||||
SetMsgEmojiLike: 'set_msg_emoji_like',
|
||||
GoCQHTTP_SendForwardMsg: 'send_forward_msg',
|
||||
MarkPrivateMsgAsRead: 'mark_private_msg_as_read',
|
||||
MarkGroupMsgAsRead: 'mark_group_msg_as_read',
|
||||
GetFriendMsgHistory: 'get_friend_msg_history',
|
||||
CreateCollection: 'create_collection',
|
||||
GetCollectionList: 'get_collection_list',
|
||||
SetLongNick: 'set_self_longnick',
|
||||
GetRecentContact: 'get_recent_contact',
|
||||
_MarkAllMsgAsRead: '_mark_all_as_read',
|
||||
GetProfileLike: 'get_profile_like',
|
||||
FetchCustomFace: 'fetch_custom_face',
|
||||
FetchEmojiLike: 'fetch_emoji_like',
|
||||
SetInputStatus: 'set_input_status',
|
||||
GetGroupInfoEx: 'get_group_info_ex',
|
||||
GetGroupIgnoreAddRequest: 'get_group_ignore_add_request',
|
||||
DelGroupNotice: '_del_group_notice',
|
||||
FetchUserProfileLike: 'fetch_user_profile_like',
|
||||
FriendPoke: 'friend_poke',
|
||||
GroupPoke: 'group_poke',
|
||||
GetPacketStatus: 'nc_get_packet_status',
|
||||
GetUserStatus: 'nc_get_user_status',
|
||||
GetRkey: 'nc_get_rkey',
|
||||
GetGroupShutList: 'get_group_shut_list',
|
||||
|
||||
GetGuildList : 'get_guild_list',
|
||||
GetGuildProfile : 'get_guild_service_profile',
|
||||
GetGuildList: 'get_guild_list',
|
||||
GetGuildProfile: 'get_guild_service_profile',
|
||||
|
||||
GetGroupIgnoredNotifies : 'get_group_ignored_notifies',
|
||||
GetGroupIgnoredNotifies: 'get_group_ignored_notifies',
|
||||
|
||||
SetGroupSign : "set_group_sign",
|
||||
SendGroupSign : "send_group_sign",
|
||||
|
||||
GetMiniAppArk : "get_mini_app_ark",
|
||||
SetGroupSign: "set_group_sign",
|
||||
SendGroupSign: "send_group_sign",
|
||||
SendPacket: "send_packet",
|
||||
GetMiniAppArk: "get_mini_app_ark",
|
||||
// UploadForwardMsg : "upload_forward_msg",
|
||||
GetAiRecord : "get_ai_record",
|
||||
GetAiCharacters : "get_ai_characters",
|
||||
SendGroupAiRecord : "send_group_ai_record",
|
||||
GetAiRecord: "get_ai_record",
|
||||
GetAiCharacters: "get_ai_characters",
|
||||
SendGroupAiRecord: "send_group_ai_record",
|
||||
|
||||
GetClientkey: "get_clientkey",
|
||||
|
||||
SendPoke: 'send_poke',
|
||||
} as const;
|
||||
|
@@ -12,16 +12,17 @@ export class OneBotFriendApi {
|
||||
}
|
||||
|
||||
//使用前预先判断 busiId 1061
|
||||
async parsePrivatePokeEvent(grayTipElement: GrayTipElement) {
|
||||
async parsePrivatePokeEvent(grayTipElement: GrayTipElement, uin: number) {
|
||||
const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr);
|
||||
let pokedetail: Array<{ uid: string }> = json.items;
|
||||
const pokedetail: Array<{ uid: string }> = json.items;
|
||||
//筛选item带有uid的元素
|
||||
pokedetail = pokedetail.filter(item => item.uid);
|
||||
if (pokedetail.length == 2) {
|
||||
const poke_uid = pokedetail.filter(item => item.uid);
|
||||
if (poke_uid.length == 2) {
|
||||
return new OB11FriendPokeEvent(
|
||||
this.core,
|
||||
parseInt((await this.core.apis.UserApi.getUinByUidV2(pokedetail[0].uid))),
|
||||
parseInt((await this.core.apis.UserApi.getUinByUidV2(pokedetail[1].uid))),
|
||||
uin,
|
||||
parseInt((await this.core.apis.UserApi.getUinByUidV2(poke_uid[0].uid))),
|
||||
parseInt((await this.core.apis.UserApi.getUinByUidV2(poke_uid[1].uid))),
|
||||
pokedetail,
|
||||
);
|
||||
}
|
||||
|
@@ -8,6 +8,8 @@ import {
|
||||
NapCatCore,
|
||||
NTGrayTipElementSubTypeV2,
|
||||
RawMessage,
|
||||
TipGroupElement,
|
||||
TipGroupElementType,
|
||||
} from '@/core';
|
||||
import { NapCatOneBot11Adapter } from '@/onebot';
|
||||
import { OB11GroupBanEvent } from '@/onebot/event/notice/OB11GroupBanEvent';
|
||||
@@ -19,8 +21,10 @@ import { OB11GroupPokeEvent } from '@/onebot/event/notice/OB11PokeEvent';
|
||||
import { OB11GroupEssenceEvent } from '@/onebot/event/notice/OB11GroupEssenceEvent';
|
||||
import { OB11GroupTitleEvent } from '@/onebot/event/notice/OB11GroupTitleEvent';
|
||||
import { OB11GroupUploadNoticeEvent } from '../event/notice/OB11GroupUploadNoticeEvent';
|
||||
import { OB11GroupNameEvent } from '../event/notice/OB11GroupNameEvent';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { FileNapCatOneBotUUID } from '@/common/helper';
|
||||
import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent';
|
||||
|
||||
export class OneBotGroupApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
@@ -204,13 +208,63 @@ export class OneBotGroupApi {
|
||||
);
|
||||
}
|
||||
|
||||
async parseGroupElement(msg: RawMessage, element: TipGroupElement, elementWrapper: GrayTipElement) {
|
||||
if (element.type === TipGroupElementType.KGROUPNAMEMODIFIED) {
|
||||
this.core.context.logger.logDebug('收到群名称变更事件', element);
|
||||
return new OB11GroupNameEvent(
|
||||
this.core,
|
||||
parseInt(msg.peerUid),
|
||||
parseInt(await this.core.apis.UserApi.getUinByUidV2(element.memberUid)),
|
||||
element.groupName,
|
||||
);
|
||||
} else if (element.type === TipGroupElementType.KSHUTUP) {
|
||||
let event = await this.parseGroupBanEvent(msg.peerUid, elementWrapper);
|
||||
return event;
|
||||
} else if (element.type === TipGroupElementType.KMEMBERADD) {
|
||||
// 自己的通知 协议推送为type->85 在这里实现为了避免邀请出现问题
|
||||
if (element.memberUid == this.core.selfInfo.uid) {
|
||||
this.core.apis.GroupApi.refreshGroupMemberCache(msg.peerUid).then().catch();
|
||||
return new OB11GroupIncreaseEvent(
|
||||
this.core,
|
||||
parseInt(msg.peerUid),
|
||||
+this.core.selfInfo.uin,
|
||||
element.adminUid ? +await this.core.apis.UserApi.getUinByUidV2(element.adminUid) : 0,
|
||||
'approve'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async parseSelfInviteEvent(msg: RawMessage, inviterUin: string, inviteeUin: string) {
|
||||
return new OB11GroupIncreaseEvent(
|
||||
this.core,
|
||||
parseInt(msg.peerUid),
|
||||
+inviteeUin,
|
||||
+inviterUin,
|
||||
'invite'
|
||||
);
|
||||
}
|
||||
|
||||
async parseGrayTipElement(msg: RawMessage, grayTipElement: GrayTipElement) {
|
||||
if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_GROUP) {
|
||||
// 解析群组事件 由sysmsg解析
|
||||
// return await this.parseGroupElement(msg, grayTipElement.groupElement, grayTipElement);
|
||||
|
||||
return await this.parseGroupElement(msg, grayTipElement.groupElement, grayTipElement);
|
||||
} else if (grayTipElement.subElementType === NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_XMLMSG) {
|
||||
// 筛选出表情回应 事件
|
||||
// 筛选自身入群情况
|
||||
// if (grayTipElement.xmlElement.busiId === '10145') {
|
||||
// const inviteData = new fastXmlParser.XMLParser({
|
||||
// ignoreAttributes: false,
|
||||
// attributeNamePrefix: '',
|
||||
// }).parse(grayTipElement.xmlElement.content);
|
||||
|
||||
// const inviterUin: string = inviteData.gtip.qq[0].jp;
|
||||
// const inviteeUin: string = inviteData.gtip.qq[1].jp;
|
||||
// //刷新群缓存
|
||||
// if (inviteeUin === this.core.selfInfo.uin) {
|
||||
// this.core.apis.GroupApi.refreshGroupMemberCache(msg.peerUid).then().catch();
|
||||
// return this.parseSelfInviteEvent(msg, inviterUin, inviteeUin);
|
||||
// }
|
||||
// } else
|
||||
if (grayTipElement.xmlElement?.templId === '10382') {
|
||||
return await this.obContext.apis.GroupApi.parseGroupEmojiLikeEventByGrayTip(msg.peerUid, grayTipElement);
|
||||
} else {
|
||||
|
@@ -17,6 +17,7 @@ import {
|
||||
SendTextElement,
|
||||
FaceType,
|
||||
GrayTipElement,
|
||||
GroupNotify,
|
||||
} from '@/core';
|
||||
import faceConfig from '@/core/external/face_config.json';
|
||||
import { NapCatOneBot11Adapter, OB11Message, OB11MessageData, OB11MessageDataType, OB11MessageFileBase, OB11MessageForward, } from '@/onebot';
|
||||
@@ -33,7 +34,9 @@ import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent';
|
||||
import { OB11GroupDecreaseEvent, GroupDecreaseSubType } from '../event/notice/OB11GroupDecreaseEvent';
|
||||
import { GroupAdmin } from '@/core/packet/transformer/proto/message/groupAdmin';
|
||||
import { OB11GroupAdminNoticeEvent } from '../event/notice/OB11GroupAdminNoticeEvent';
|
||||
import { GroupChange, GroupChangeInfo, PushMsgBody } from '@/core/packet/transformer/proto';
|
||||
import { GroupChange, GroupChangeInfo, GroupInvite, PushMsgBody } from '@/core/packet/transformer/proto';
|
||||
import { OB11GroupRequestEvent } from '../event/request/OB11GroupRequest';
|
||||
import { LRUCache } from '@/common/lru-cache';
|
||||
|
||||
type RawToOb11Converters = {
|
||||
[Key in keyof MessageElement as Key extends `${string}Element` ? Key : never]: (
|
||||
@@ -67,7 +70,8 @@ function keyCanBeParsed(key: string, parser: RawToOb11Converters): key is keyof
|
||||
export class OneBotMsgApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
core: NapCatCore;
|
||||
|
||||
notifyGroupInvite: LRUCache<string, GroupNotify> = new LRUCache(50);
|
||||
// seq -> notify
|
||||
rawToOb11Converters: RawToOb11Converters = {
|
||||
textElement: async element => {
|
||||
if (element.atType === NTMsgAtType.ATTYPEUNKNOWN) {
|
||||
@@ -679,7 +683,7 @@ export class OneBotMsgApi {
|
||||
async parsePrivateMsgEvent(msg: RawMessage, grayTipElement: GrayTipElement) {
|
||||
if (grayTipElement.subElementType == NTGrayTipElementSubTypeV2.GRAYTIP_ELEMENT_SUBTYPE_JSON) {
|
||||
if (grayTipElement.jsonGrayTipElement.busiId == 1061) {
|
||||
const PokeEvent = await this.obContext.apis.FriendApi.parsePrivatePokeEvent(grayTipElement);
|
||||
const PokeEvent = await this.obContext.apis.FriendApi.parsePrivatePokeEvent(grayTipElement, Number(await this.core.apis.UserApi.getUinByUidV2(msg.peerUid)));
|
||||
if (PokeEvent) { return PokeEvent; };
|
||||
} else if (grayTipElement.jsonGrayTipElement.busiId == 19324 && msg.peerUid !== '') {
|
||||
return new OB11FriendAddNoticeEvent(this.core, Number(await this.core.apis.UserApi.getUinByUidV2(msg.peerUid)));
|
||||
@@ -895,16 +899,16 @@ export class OneBotMsgApi {
|
||||
const calculateTotalSize = async (elements: SendMessageElement[]): Promise<number> => {
|
||||
const sizePromises = elements.map(async element => {
|
||||
switch (element.elementType) {
|
||||
case ElementType.PTT:
|
||||
return (await fsPromise.stat(element.pttElement.filePath)).size;
|
||||
case ElementType.FILE:
|
||||
return (await fsPromise.stat(element.fileElement.filePath)).size;
|
||||
case ElementType.VIDEO:
|
||||
return (await fsPromise.stat(element.videoElement.filePath)).size;
|
||||
case ElementType.PIC:
|
||||
return (await fsPromise.stat(element.picElement.sourcePath)).size;
|
||||
default:
|
||||
return 0;
|
||||
case ElementType.PTT:
|
||||
return (await fsPromise.stat(element.pttElement.filePath)).size;
|
||||
case ElementType.FILE:
|
||||
return (await fsPromise.stat(element.fileElement.filePath)).size;
|
||||
case ElementType.VIDEO:
|
||||
return (await fsPromise.stat(element.videoElement.filePath)).size;
|
||||
case ElementType.PIC:
|
||||
return (await fsPromise.stat(element.picElement.sourcePath)).size;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
const sizes = await Promise.all(sizePromises);
|
||||
@@ -968,25 +972,55 @@ export class OneBotMsgApi {
|
||||
|
||||
return { path, fileName: inputdata.name ?? fileName };
|
||||
}
|
||||
|
||||
groupChangDecreseType2String(type: number): GroupDecreaseSubType {
|
||||
switch (type) {
|
||||
case 130:
|
||||
return 'leave';
|
||||
case 131:
|
||||
return 'kick';
|
||||
case 3:
|
||||
return 'kick_me';
|
||||
default:
|
||||
return 'kick';
|
||||
case 130:
|
||||
return 'leave';
|
||||
case 131:
|
||||
return 'kick';
|
||||
case 3:
|
||||
return 'kick_me';
|
||||
default:
|
||||
return 'kick';
|
||||
}
|
||||
}
|
||||
|
||||
async waitGroupNotify(groupUin: string, memberUid?: string, operatorUid?: string) {
|
||||
let groupRole = this.core.apis.GroupApi.groupMemberCache.get(groupUin)?.get(this.core.selfInfo.uid.toString())?.role;
|
||||
let isAdminOrOwner = groupRole === 3 || groupRole === 4;
|
||||
|
||||
if (isAdminOrOwner && !operatorUid) {
|
||||
let dataNotify: GroupNotify | undefined;
|
||||
await this.core.eventWrapper.registerListen('NodeIKernelGroupListener/onGroupNotifiesUpdated',
|
||||
(doubt, notifies) => {
|
||||
for (const notify of notifies) {
|
||||
if (notify.group.groupCode === groupUin && notify.user1.uid === memberUid) {
|
||||
dataNotify = notify;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}, 1, 1000).catch(undefined);
|
||||
if (dataNotify) {
|
||||
return !dataNotify.actionUser.uid ? dataNotify.user2.uid : dataNotify.actionUser.uid;
|
||||
}
|
||||
}
|
||||
|
||||
return operatorUid;
|
||||
}
|
||||
|
||||
async parseSysMessage(msg: number[]) {
|
||||
const SysMessage = new NapProtoMsg(PushMsgBody).decode(Uint8Array.from(msg));
|
||||
// 邀请需要解grayTipElement
|
||||
if (SysMessage.contentHead.type == 33 && SysMessage.body?.msgContent) {
|
||||
const groupChange = new NapProtoMsg(GroupChange).decode(SysMessage.body.msgContent);
|
||||
this.core.apis.GroupApi.refreshGroupMemberCache(groupChange.groupUin.toString()).then().catch();
|
||||
const operatorUid = groupChange.operatorInfo?.toString();
|
||||
let operatorUid = await this.waitGroupNotify(
|
||||
groupChange.groupUin.toString(),
|
||||
groupChange.memberUid,
|
||||
groupChange.operatorInfo ? Buffer.from(groupChange.operatorInfo).toString() : ''
|
||||
);
|
||||
return new OB11GroupIncreaseEvent(
|
||||
this.core,
|
||||
groupChange.groupUin,
|
||||
@@ -994,12 +1028,17 @@ export class OneBotMsgApi {
|
||||
operatorUid ? +await this.core.apis.UserApi.getUinByUidV2(operatorUid) : 0,
|
||||
groupChange.decreaseType == 131 ? 'invite' : 'approve',
|
||||
);
|
||||
|
||||
} else if (SysMessage.contentHead.type == 34 && SysMessage.body?.msgContent) {
|
||||
const groupChange = new NapProtoMsg(GroupChange).decode(SysMessage.body.msgContent);
|
||||
// 自身被踢出时operatorInfo会是一个protobuf 否则大多数情况为一个string
|
||||
const operatorUid = groupChange.decreaseType === 3 && groupChange.operatorInfo ?
|
||||
new NapProtoMsg(GroupChangeInfo).decode(groupChange.operatorInfo).operator?.operatorUid :
|
||||
groupChange.operatorInfo?.toString();
|
||||
let operatorUid = await this.waitGroupNotify(
|
||||
groupChange.groupUin.toString(),
|
||||
groupChange.memberUid,
|
||||
groupChange.decreaseType === 3 && groupChange.operatorInfo ?
|
||||
new NapProtoMsg(GroupChangeInfo).decode(groupChange.operatorInfo).operator?.operatorUid :
|
||||
groupChange.operatorInfo?.toString()
|
||||
);
|
||||
if (groupChange.memberUid === this.core.selfInfo.uid) {
|
||||
setTimeout(() => {
|
||||
this.core.apis.GroupApi.groupMemberCache.delete(groupChange.groupUin.toString());
|
||||
@@ -1033,6 +1072,72 @@ export class OneBotMsgApi {
|
||||
+await this.core.apis.UserApi.getUinByUidV2(uid),
|
||||
enabled ? 'set' : 'unset'
|
||||
);
|
||||
} else if (SysMessage.contentHead.type == 87 && SysMessage.body?.msgContent) {
|
||||
let groupInvite = new NapProtoMsg(GroupInvite).decode(SysMessage.body.msgContent);
|
||||
let request_seq = '';
|
||||
try {
|
||||
await this.core.eventWrapper.registerListen('NodeIKernelMsgListener/onRecvMsg', (msgs) => {
|
||||
for (const msg of msgs) {
|
||||
if (msg.senderUid === groupInvite.invitorUid && msg.msgType === 11) {
|
||||
let jumpUrl = JSON.parse(msg.elements.find(e => e.elementType === 10)?.arkElement?.bytesData ?? '').meta?.news?.jumpUrl;
|
||||
let jumpUrlParams = new URLSearchParams(jumpUrl);
|
||||
let groupcode = jumpUrlParams.get('groupcode');
|
||||
let receiveruin = jumpUrlParams.get('receiveruin');
|
||||
let msgseq = jumpUrlParams.get('msgseq');
|
||||
request_seq = msgseq ?? '';
|
||||
if (groupcode === groupInvite.groupUin.toString() && receiveruin === this.core.selfInfo.uin) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}, 1, 1000);
|
||||
} catch (error) {
|
||||
request_seq = '';
|
||||
}
|
||||
// 未拉取到seq
|
||||
if (request_seq === '') {
|
||||
return;
|
||||
}
|
||||
// 创建个假的
|
||||
this.notifyGroupInvite.put(request_seq, {
|
||||
seq: request_seq,
|
||||
type: 1,
|
||||
group: {
|
||||
groupCode: groupInvite.groupUin.toString(),
|
||||
groupName: '',
|
||||
},
|
||||
user1: {
|
||||
uid: groupInvite.invitorUid,
|
||||
nickName: '',
|
||||
},
|
||||
user2: {
|
||||
uid: this.core.selfInfo.uid,
|
||||
nickName: '',
|
||||
},
|
||||
actionUser: {
|
||||
uid: groupInvite.invitorUid,
|
||||
nickName: '',
|
||||
},
|
||||
actionTime: Date.now().toString(),
|
||||
postscript: '',
|
||||
repeatSeqs: [],
|
||||
warningTips: '',
|
||||
invitationExt: {
|
||||
srcType: 1,
|
||||
groupCode: groupInvite.groupUin.toString(),
|
||||
waitStatus: 1,
|
||||
},
|
||||
status: 1
|
||||
})
|
||||
return new OB11GroupRequestEvent(
|
||||
this.core,
|
||||
+groupInvite.groupUin,
|
||||
+await this.core.apis.UserApi.getUinByUidV2(groupInvite.invitorUid),
|
||||
'invite',
|
||||
'',
|
||||
request_seq
|
||||
);
|
||||
} else if (SysMessage.contentHead.type == 528 && SysMessage.contentHead.subType == 39 && SysMessage.body?.msgContent) {
|
||||
return await this.obContext.apis.UserApi.parseLikeEvent(SysMessage.body?.msgContent);
|
||||
}
|
||||
|
@@ -91,11 +91,13 @@ export class OneBotQuickActionApi {
|
||||
}
|
||||
|
||||
async handleGroupRequest(request: OB11GroupRequestEvent, quickAction: QuickActionGroupRequest) {
|
||||
const noify = await this.findNotify(request.flag);
|
||||
|
||||
let invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(request.flag);
|
||||
const notify = invite_notify ?? await this.findNotify(request.flag);
|
||||
|
||||
if (!isNull(quickAction.approve) && noify) {
|
||||
if (!isNull(quickAction.approve) && notify) {
|
||||
this.core.apis.GroupApi.handleGroupRequest(
|
||||
noify,
|
||||
notify,
|
||||
quickAction.approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
|
||||
quickAction.reason,
|
||||
).catch(e => this.core.context.logger.logError(e));
|
||||
|
13
src/onebot/event/notice/OB11GroupNameEvent.ts
Normal file
13
src/onebot/event/notice/OB11GroupNameEvent.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { OB11GroupNoticeEvent } from './OB11GroupNoticeEvent';
|
||||
import { NapCatCore } from '@/core';
|
||||
|
||||
export class OB11GroupNameEvent extends OB11GroupNoticeEvent {
|
||||
notice_type = 'notify';
|
||||
sub_type = 'group_name';
|
||||
name_new: string;
|
||||
|
||||
constructor(core: NapCatCore, groupId: number, userId: number, nameNew: string) {
|
||||
super(core, groupId, userId);
|
||||
this.name_new = nameNew;
|
||||
}
|
||||
}
|
@@ -10,12 +10,14 @@ class OB11PokeEvent extends OB11BaseNoticeEvent {
|
||||
|
||||
export class OB11FriendPokeEvent extends OB11PokeEvent {
|
||||
raw_info: any;
|
||||
sender_id: number;
|
||||
|
||||
//raw_message nb等框架标准为string
|
||||
constructor(core: NapCatCore, user_id: number, target_id: number, raw_message: any) {
|
||||
constructor(core: NapCatCore, user_id: number, sender_id: number, target_id: number, raw_message: any) {
|
||||
super(core);
|
||||
this.target_id = target_id;
|
||||
this.user_id = user_id;
|
||||
this.sender_id = sender_id;
|
||||
this.raw_info = raw_message;
|
||||
}
|
||||
}
|
||||
|
@@ -164,6 +164,7 @@ export class NapCatOneBot11Adapter {
|
||||
this.initBuddyListener();
|
||||
this.initGroupListener();
|
||||
|
||||
WebUiDataRuntime.setQQVersion(this.core.context.basicInfoWrapper.getFullQQVesion());
|
||||
WebUiDataRuntime.setQQLoginInfo(selfInfo);
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setOnOB11ConfigChanged(async (newConfig) => {
|
||||
@@ -310,7 +311,7 @@ export class NapCatOneBot11Adapter {
|
||||
guildId: ''
|
||||
};
|
||||
const msg = (await this.core.apis.MsgApi.queryMsgsWithFilterExWithSeq(peer, msgSeq)).msgList.find(e => e.msgType == NTMsgType.KMSGTYPEGRAYTIPS);
|
||||
const element = msg?.elements[0];
|
||||
const element = msg?.elements.find(e => !!e.grayTipElement?.revokeElement);
|
||||
if (msg && element) {
|
||||
const recallEvent = await this.emitRecallMsg(msg, element);
|
||||
try {
|
||||
@@ -467,6 +468,10 @@ export class NapCatOneBot11Adapter {
|
||||
}
|
||||
|
||||
private async handleMsg(message: RawMessage, network: Array<AdapterConfigWrap>) {
|
||||
// 过滤无效消息
|
||||
if (message.msgType === NTMsgType.KMSGTYPENULL) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const ob11Msg = await this.apis.MsgApi.parseMessageV2(message, this.configLoader.configData.parseMultMsg);
|
||||
if (ob11Msg) {
|
||||
|
@@ -17,7 +17,6 @@ export class OB11PassiveWebSocketAdapter extends IOB11NetworkAdapter<WebsocketSe
|
||||
wsServer: WebSocketServer;
|
||||
wsClients: WebSocket[] = [];
|
||||
wsClientsMutex = new Mutex();
|
||||
heartbeatInterval: number = 0;
|
||||
private heartbeatIntervalId: NodeJS.Timeout | null = null;
|
||||
wsClientWithEvent: WebSocket[] = [];
|
||||
|
||||
@@ -100,7 +99,7 @@ export class OB11PassiveWebSocketAdapter extends IOB11NetworkAdapter<WebsocketSe
|
||||
this.logger.log('[OneBot] [WebSocket Server] Server Started', typeof (addressInfo) === 'string' ? addressInfo : addressInfo?.address + ':' + addressInfo?.port);
|
||||
|
||||
this.isEnable = true;
|
||||
if (this.heartbeatInterval > 0) {
|
||||
if (this.config.heartInterval > 0) {
|
||||
this.registerHeartBeat();
|
||||
}
|
||||
|
||||
@@ -134,11 +133,11 @@ export class OB11PassiveWebSocketAdapter extends IOB11NetworkAdapter<WebsocketSe
|
||||
this.wsClientsMutex.runExclusive(async () => {
|
||||
this.wsClientWithEvent.forEach((wsClient) => {
|
||||
if (wsClient.readyState === WebSocket.OPEN) {
|
||||
wsClient.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.heartbeatInterval, this.core.selfInfo.online ?? true, true)));
|
||||
wsClient.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.config.heartInterval, this.core.selfInfo.online ?? true, true)));
|
||||
}
|
||||
});
|
||||
});
|
||||
}, this.heartbeatInterval);
|
||||
}, this.config.heartInterval);
|
||||
}
|
||||
|
||||
private authorize(token: string | undefined, wsClient: WebSocket, wsReq: IncomingMessage) {
|
||||
@@ -185,7 +184,7 @@ export class OB11PassiveWebSocketAdapter extends IOB11NetworkAdapter<WebsocketSe
|
||||
const wasEnabled = this.isEnable;
|
||||
const oldPort = this.config.port;
|
||||
const oldHost = this.config.host;
|
||||
const oldHeartbeatInterval = this.heartbeatInterval;
|
||||
const oldHeartbeatInterval = this.config.heartInterval;
|
||||
this.config = newConfig;
|
||||
|
||||
if (newConfig.enable && !wasEnabled) {
|
||||
@@ -214,7 +213,6 @@ export class OB11PassiveWebSocketAdapter extends IOB11NetworkAdapter<WebsocketSe
|
||||
clearInterval(this.heartbeatIntervalId);
|
||||
this.heartbeatIntervalId = null;
|
||||
}
|
||||
this.heartbeatInterval = newConfig.heartInterval;
|
||||
if (newConfig.heartInterval > 0 && this.isEnable) {
|
||||
this.registerHeartBeat();
|
||||
}
|
||||
|
@@ -29,9 +29,11 @@ import { InitWebUi } from '@/webui';
|
||||
import { WebUiDataRuntime } from '@/webui/src/helper/Data';
|
||||
import { napCatVersion } from '@/common/version';
|
||||
import { NodeIO3MiscListener } from '@/core/listeners/NodeIO3MiscListener';
|
||||
import { UmamiTrace } from '@/common/umami';
|
||||
// NapCat Shell App ES 入口文件
|
||||
async function handleUncaughtExceptions(logger: LogWrapper) {
|
||||
process.on('uncaughtException', (err) => {
|
||||
UmamiTrace.sendTrace('uncaught/error', err.message);
|
||||
logger.logError('[NapCat] [Error] Unhandled Exception:', err.message);
|
||||
});
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
@@ -151,8 +153,9 @@ async function handleLogin(
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number, errMsg: string) => {
|
||||
UmamiTrace.sendTrace('qrlogin/error', [errType, errCode, errMsg].toString());
|
||||
if (!isLogined) {
|
||||
logger.logError('[Core] [Login] Login Error,ErrCode: ', errCode, ' ErrMsg:', errMsg);
|
||||
logger.logError('[Core] [Login] Login Error,ErrType: ', errType, ' ErrCode:', errCode);
|
||||
if (errType == 1 && errCode == 3) {
|
||||
// 二维码过期刷新
|
||||
}
|
||||
@@ -160,8 +163,9 @@ async function handleLogin(
|
||||
}
|
||||
};
|
||||
|
||||
loginListener.onLoginFailed = (args) => {
|
||||
logger.logError('[Core] [Login] Login Error , ErrInfo: ', args);
|
||||
loginListener.onLoginFailed = (...args) => {
|
||||
UmamiTrace.sendTrace('login/error', args.toString());
|
||||
logger.logError('[Core] [Login] Login Error , ErrInfo: ', JSON.stringify(args));
|
||||
};
|
||||
|
||||
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
|
||||
@@ -222,7 +226,7 @@ async function handleLogin(
|
||||
logger.log(`可用于快速登录的 QQ:\n${historyLoginList
|
||||
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
|
||||
.join('\n')
|
||||
}`);
|
||||
}`);
|
||||
}
|
||||
loginService.getQRCodePicture();
|
||||
}
|
||||
@@ -266,7 +270,6 @@ export async function NCoreInitShell() {
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
handleUncaughtExceptions(logger);
|
||||
|
||||
const basicInfoWrapper = new QQBasicInfoWrapper({ logger });
|
||||
const wrapper = loadQQWrapper(basicInfoWrapper.getFullQQVesion());
|
||||
|
||||
@@ -295,9 +298,10 @@ export async function NCoreInitShell() {
|
||||
|
||||
const dataTimestape = new Date().getTime().toString();
|
||||
o3Service.reportAmgomWeather('login', 'a1', [dataTimestape, '0', '0']);
|
||||
|
||||
UmamiTrace.init(basicInfoWrapper.getFullQQVesion(), loginService.getMachineGuid(), 'shell');
|
||||
UmamiTrace.sendTrace('boot/init');
|
||||
const selfInfo = await handleLogin(loginService, logger, pathWrapper, quickLoginUin, historyLoginList);
|
||||
|
||||
UmamiTrace.sendTrace('login/success');
|
||||
const amgomDataPiece = 'eb1fd6ac257461580dc7438eb099f23aae04ca679f4d88f53072dc56e3bb1129';
|
||||
o3Service.setAmgomDataPiece(basicInfoWrapper.QQVersionAppid, new Uint8Array(Buffer.from(amgomDataPiece, 'hex')));
|
||||
|
||||
|
@@ -7,3 +7,9 @@ export const PackageInfoHandler: RequestHandler = (_, res) => {
|
||||
const data = WebUiDataRuntime.getPackageJson();
|
||||
sendSuccess(res, data);
|
||||
};
|
||||
|
||||
|
||||
export const QQVersionHandler: RequestHandler = (_, res) => {
|
||||
const data = WebUiDataRuntime.getQQVersion();
|
||||
sendSuccess(res, data);
|
||||
};
|
||||
|
19
src/webui/src/api/Status.ts
Normal file
19
src/webui/src/api/Status.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { RequestHandler } from 'express';
|
||||
import { SystemStatus, statusHelperSubscription } from "@/core/helper/status";
|
||||
|
||||
export const StatusRealTimeHandler: RequestHandler = async (req, res) => {
|
||||
res.setHeader('Content-Type', 'text/event-stream');
|
||||
res.setHeader('Connection', 'keep-alive');
|
||||
const sendStatus = (status: SystemStatus) => {
|
||||
try{
|
||||
res.write(`data: ${JSON.stringify(status)}\n\n`);
|
||||
} catch (e) {
|
||||
console.error(`An error occurred when writing sendStatus data to client: ${e}`);
|
||||
}
|
||||
};
|
||||
statusHelperSubscription.on('statusUpdate', sendStatus);
|
||||
req.on('close', () => {
|
||||
statusHelperSubscription.off('statusUpdate', sendStatus);
|
||||
res.end();
|
||||
});
|
||||
};
|
@@ -11,6 +11,7 @@ const LoginRuntime: LoginRuntimeType = {
|
||||
uin: '',
|
||||
nick: '',
|
||||
},
|
||||
QQVersion: 'unknown',
|
||||
NapCatHelper: {
|
||||
onOB11ConfigChanged: async () => {
|
||||
return;
|
||||
@@ -100,4 +101,12 @@ export const WebUiDataRuntime = {
|
||||
getPackageJson() {
|
||||
return LoginRuntime.packageJson;
|
||||
},
|
||||
|
||||
setQQVersion(version: string) {
|
||||
LoginRuntime.QQVersion = version;
|
||||
},
|
||||
|
||||
getQQVersion() {
|
||||
return LoginRuntime.QQVersion;
|
||||
}
|
||||
};
|
||||
|
@@ -90,7 +90,7 @@ export class WebUiConfigWrapper {
|
||||
try {
|
||||
const configPath = resolve(webUiPathWrapper.configPath, './webui.json');
|
||||
|
||||
if (!await fs.access(configPath, constants.R_OK | constants.W_OK).then(() => true).catch(() => false)) {
|
||||
if (!await fs.access(configPath, constants.F_OK).then(() => true).catch(() => false)) {
|
||||
await fs.writeFile(configPath, JSON.stringify(defaultconfig, null, 4));
|
||||
}
|
||||
|
||||
@@ -101,7 +101,12 @@ export class WebUiConfigWrapper {
|
||||
if (!parsedConfig.prefix.startsWith('/')) parsedConfig.prefix = '/' + parsedConfig.prefix;
|
||||
if (parsedConfig.prefix.endsWith('/')) parsedConfig.prefix = parsedConfig.prefix.slice(0, -1);
|
||||
// 配置已经被操作过了,还是回写一下吧,不然新配置不会出现在配置文件里
|
||||
await fs.writeFile(configPath, JSON.stringify(parsedConfig, null, 4));
|
||||
if (await fs.access(configPath, constants.W_OK).then(() => true).catch(() => false)) {
|
||||
await fs.writeFile(configPath, JSON.stringify(parsedConfig, null, 4));
|
||||
}
|
||||
else {
|
||||
console.warn(`文件: ${configPath} 没有写入权限, 配置的更改部分可能会在重启后还原.`);
|
||||
}
|
||||
// 不希望回写的配置放后面
|
||||
|
||||
// 查询主机地址是否可用
|
||||
|
@@ -1,8 +1,11 @@
|
||||
import { Router } from 'express';
|
||||
import { PackageInfoHandler } from '../api/BaseInfo';
|
||||
import { PackageInfoHandler, QQVersionHandler } from '../api/BaseInfo';
|
||||
import { StatusRealTimeHandler } from "@webapi/api/Status";
|
||||
|
||||
const router = Router();
|
||||
// router: 获取nc的package.json信息
|
||||
router.get('/QQVersion', QQVersionHandler);
|
||||
router.get('/PackageInfo', PackageInfoHandler);
|
||||
router.get('/GetSysStatusRealTime', StatusRealTimeHandler);
|
||||
|
||||
export { router as BaseRouter };
|
||||
|
2
src/webui/src/types/data.d.ts
vendored
2
src/webui/src/types/data.d.ts
vendored
@@ -1,4 +1,5 @@
|
||||
import type { LoginListItem, SelfInfo } from '@/core';
|
||||
import type { OneBotConfig } from "@/onebot/config/config";
|
||||
|
||||
interface LoginRuntimeType {
|
||||
LoginCurrentTime: number;
|
||||
@@ -7,6 +8,7 @@ interface LoginRuntimeType {
|
||||
QQQRCodeURL: string;
|
||||
QQLoginUin: string;
|
||||
QQLoginInfo: SelfInfo;
|
||||
QQVersion: string;
|
||||
NapCatHelper: {
|
||||
onQuickLoginRequested: (uin: string) => Promise<{ result: boolean; message: string }>;
|
||||
onOB11ConfigChanged: (ob11: OneBotConfig) => Promise<void>;
|
||||
|
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"target": "ES2021",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": [
|
||||
"ES2020",
|
||||
"ES2021",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
|
Reference in New Issue
Block a user