mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
49 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
2256d67e2b | ||
![]() |
0af0bdede6 | ||
![]() |
379f31b9de | ||
![]() |
771a524734 | ||
![]() |
560e18a610 | ||
![]() |
147bdfab95 | ||
![]() |
36b1b0f663 | ||
![]() |
91511e4c3f | ||
![]() |
6a72056b25 | ||
![]() |
62e0c57a50 | ||
![]() |
9d92270931 | ||
![]() |
f61321d5a6 | ||
![]() |
08ab2f8649 | ||
![]() |
82962c4b42 | ||
![]() |
bd24e8a4ad | ||
![]() |
6224d9a292 | ||
![]() |
bbc58f3671 | ||
![]() |
fcd620283f | ||
![]() |
a78def3d2d | ||
![]() |
43e94a5db0 | ||
![]() |
e77bcc1267 | ||
![]() |
9b458958b8 | ||
![]() |
35419ade29 | ||
![]() |
15bd2ee887 | ||
![]() |
9394bafa8e | ||
![]() |
94150a0c48 | ||
![]() |
8955fdfc23 | ||
![]() |
c13aa6a545 | ||
![]() |
c73b50bd4a | ||
![]() |
0a17a38bf1 | ||
![]() |
0f7bfe1d66 | ||
![]() |
cf3f488663 | ||
![]() |
5f536fdb73 | ||
![]() |
99d0b13cce | ||
![]() |
b04937f012 | ||
![]() |
91c9b059cf | ||
![]() |
35cc643440 | ||
![]() |
b23bb8c46a | ||
![]() |
64fdf62c4b | ||
![]() |
1c8a808571 | ||
![]() |
d8f0295032 | ||
![]() |
d59771ac2f | ||
![]() |
45df093fac | ||
![]() |
fba2078fc0 | ||
![]() |
20a37fe2de | ||
![]() |
8f6d26b65c | ||
![]() |
b58a194c8a | ||
![]() |
52f1b0a0ce | ||
![]() |
c2b8fb223b |
15
README.md
15
README.md
@@ -12,13 +12,6 @@ NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现。
|
||||
- [x] **低占用**:无头模式占用资源极低,适合在服务器上运行
|
||||
- [x] **WebUI**:自带 WebUI 支持,远程管理更加便捷
|
||||
|
||||
### V2 Roadmap
|
||||
|
||||
- **依赖注入**:彻底理清模块间依赖,明确加载顺序,根除滥用变量导出、`setTimeout` 初始化
|
||||
- **ES 出包**:可读性更高,报错更可读
|
||||
- **代码优化**:减少代码冗余,提高代码质量
|
||||
- **输出标准化**:统一控制台输出格式
|
||||
|
||||
## 如何使用
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
|
||||
@@ -30,12 +23,12 @@ NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现。
|
||||
[Telegram Link](https://t.me/+nLZEnpne-pQ1OWFl)
|
||||
|
||||
## 鸣谢名单
|
||||
感谢 [LLOneBot](https://github.com/LLOneBot/LLOneBot) 提供初始版本基础
|
||||
|
||||
[Lagrange](https://github.com/LagrangeDev/Lagrange.Core)
|
||||
感谢 [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持
|
||||
|
||||
---
|
||||
|
||||
**任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**
|
||||
## 使用许可
|
||||
|
||||
## 附加协议
|
||||
禁止任何项目使用core部分代码用于二次开发与分发
|
||||
任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**此外,禁止任何项目未经授权二次分发或基于 [core](./src/core) 部分代码开发。**
|
||||
|
@@ -3,8 +3,8 @@
|
||||
"type": "extension",
|
||||
"name": "NapCat",
|
||||
"slug": "NapCat",
|
||||
"description": "OneBot v11 protocol implementation with NapCat logic",
|
||||
"version": "2.0.1",
|
||||
"description": "现代化的 OneBot 11 协议实现",
|
||||
"version": "2.0.12",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
@@ -30,4 +30,4 @@
|
||||
"main": "./liteloader.cjs",
|
||||
"preload": "./preload.cjs"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "2.0.1",
|
||||
"version": "2.0.12",
|
||||
"scripts": {
|
||||
"build:framework": "vite build --mode framework",
|
||||
"build:shell": "vite build --mode shell",
|
||||
|
77
script/BootWay05_init.bat
Normal file
77
script/BootWay05_init.bat
Normal file
@@ -0,0 +1,77 @@
|
||||
@echo off
|
||||
REM Check if the script is running as administrator
|
||||
openfiles >nul 2>&1
|
||||
if %errorlevel% neq 0 (
|
||||
REM If not, restart the script in administrator mode
|
||||
echo Requesting administrator privileges...
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/c %~f0 %*' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
|
||||
cd /d %~dp0
|
||||
|
||||
set currentPath=%cd%
|
||||
set currentPath=%currentPath:\=/%
|
||||
|
||||
REM Generate JavaScript code
|
||||
set "jsCode=(async () =^>await import('file:///%currentPath%/napcat.mjs'))();"
|
||||
|
||||
REM Save JavaScript code to a file
|
||||
echo %jsCode% > loadScript.js
|
||||
echo JavaScript code has been generated and saved to loadScript.js
|
||||
|
||||
REM Set NAPCAT_PATH environment variable to the address of loadScript.js in the current directory
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Get QQ path and cache it
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%b"
|
||||
)
|
||||
|
||||
set "pathWithoutUninstall=%RetString:Uninstall.exe=%"
|
||||
|
||||
SET QQPath=%pathWithoutUninstall%QQ.exe
|
||||
echo %QQPath%>qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been cached to qq_path_cache.txt
|
||||
|
||||
REM Exit if QQ path is invalid
|
||||
if not exist "%QQpath%" (
|
||||
echo provided QQ path is invalid: %QQpath%
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
|
||||
REM Collect dbghelp.dll path and HASH information
|
||||
set QQdir=%~dp0
|
||||
set oldDllPath=%QQdir%dbghelp.dll
|
||||
set newDllPath=%currentPath%\dbghelp.dll
|
||||
|
||||
for /f "tokens=*" %%A in ('certutil -hashfile "%oldDllPath%" MD5') do (
|
||||
if not defined oldDllHash set oldDllHash=%%A
|
||||
)
|
||||
for /f "tokens=*" %%A in ('certutil -hashfile "%newDllPath%" MD5') do (
|
||||
if not defined newDllHash set newDllHash=%%A
|
||||
)
|
||||
|
||||
REM Compare the HASH of the old and new dbghelp.dll, and replace the old one if they are different
|
||||
if "%oldDllHash%" neq "%newDllHash%" (
|
||||
tasklist /fi "imagename eq QQ.exe" 2>nul | find /i "QQ.exe" >nul
|
||||
if %errorlevel% equ 0 (
|
||||
REM If the file is in use, prompt the user to close QQ
|
||||
echo dbghelp.dll is in use, please close QQ first.
|
||||
) else (
|
||||
copy /y "%newDllPath%" "%oldDllPath%"
|
||||
if %errorlevel% neq 0 (
|
||||
echo Copy dbghelp.dll failed, please check and try again.
|
||||
pause
|
||||
exit /b
|
||||
) else (
|
||||
echo dbghelp.dll has been updated.
|
||||
echo Please run BootWay05_run.bat to start QQ.
|
||||
echo If you update QQ in the future, please run BootWay05_init.bat again.
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
)
|
||||
)
|
10
script/BootWay05_run.bat
Normal file
10
script/BootWay05_run.bat
Normal file
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
set /p QQPath=<qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been read from qq_path_cache.txt
|
||||
echo If failed to start QQ, please try running this script in administrator mode.
|
||||
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Launch QQ.exe with params provided
|
||||
|
||||
"%QQPath%" --enable-logging %*
|
13
script/BootWay05_run.utf8.bat
Normal file
13
script/BootWay05_run.utf8.bat
Normal file
@@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
|
||||
chcp 65001
|
||||
|
||||
set /p QQPath=<qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been read from qq_path_cache.txt
|
||||
echo If failed to start QQ, please try running this script in administrator mode.
|
||||
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Launch QQ.exe with params provided
|
||||
|
||||
"%QQPath%" --enable-logging %*
|
@@ -2,7 +2,7 @@ import path, { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
|
||||
export const napcat_version = '2.0.1';
|
||||
export const napcat_version = '2.0.12';
|
||||
|
||||
export class NapCatPathWrapper {
|
||||
binaryPath: string;
|
||||
|
31
src/common/utils/LRU.ts
Normal file
31
src/common/utils/LRU.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
export class LRUCache<K, V> {
|
||||
private capacity: number;
|
||||
private cache: Map<K, V>;
|
||||
|
||||
constructor(capacity: number) {
|
||||
this.capacity = capacity;
|
||||
this.cache = new Map<K, V>();
|
||||
}
|
||||
|
||||
public get(key: K): V | undefined {
|
||||
const value = this.cache.get(key);
|
||||
if (value !== undefined) {
|
||||
// Move the accessed key to the end to mark it as most recently used
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public put(key: K, value: V): void {
|
||||
if (this.cache.has(key)) {
|
||||
// If the key already exists, move it to the end to mark it as most recently used
|
||||
this.cache.delete(key);
|
||||
} else if (this.cache.size >= this.capacity) {
|
||||
// If the cache is full, remove the least recently used key (the first one in the map)
|
||||
const firstKey = this.cache.keys().next().value;
|
||||
this.cache.delete(firstKey);
|
||||
}
|
||||
this.cache.set(key, value);
|
||||
}
|
||||
}
|
@@ -2,6 +2,7 @@ import log4js, { Configuration } from 'log4js';
|
||||
import { truncateString } from '@/common/utils/helper';
|
||||
import path from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { AtType, ChatType, ElementType, ElementWrapper, RawMessage, SelfInfo } from '@/core';
|
||||
|
||||
export enum LogLevel {
|
||||
DEBUG = 'debug',
|
||||
@@ -135,4 +136,104 @@ export class LogWrapper {
|
||||
logFatal(...args: any[]) {
|
||||
this._log(LogLevel.FATAL, ...args);
|
||||
}
|
||||
|
||||
logMessage(msg: RawMessage, selfInfo: SelfInfo) {
|
||||
const isSelfSent = msg.senderUin === selfInfo.uin;
|
||||
this.log(`${
|
||||
isSelfSent ? '发送 ->' : '接收 <-'
|
||||
} ${rawMessageToText(msg)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function rawMessageToText(msg: RawMessage, recursiveLevel = 0): string {
|
||||
if (recursiveLevel > 2) {
|
||||
return '...';
|
||||
}
|
||||
|
||||
const tokens: string[] = [];
|
||||
|
||||
if (msg.chatType == ChatType.friend) {
|
||||
tokens.push(`私聊 (${msg.peerUin})`);
|
||||
} else if (msg.chatType == ChatType.group) {
|
||||
tokens.push(`群聊 (群 ${msg.peerUin} 的 ${msg.senderUin})`);
|
||||
} else if (msg.chatType == ChatType.chatDevice) {
|
||||
tokens.push('移动设备');
|
||||
} else /* temp */ {
|
||||
tokens.push(`临时消息 (${msg.peerUin})`);
|
||||
}
|
||||
|
||||
// message content
|
||||
|
||||
function msgElementToText(element: ElementWrapper) {
|
||||
if (element.textElement) {
|
||||
if (element.textElement.atType === AtType.notAt) {
|
||||
return element.textElement.content;
|
||||
} else if (element.textElement.atType === AtType.atAll) {
|
||||
return `@全体成员`;
|
||||
} else if (element.textElement.atType === AtType.atUser) {
|
||||
return `${element.textElement.content} (${element.textElement.atUid})`;
|
||||
}
|
||||
}
|
||||
|
||||
if (element.replyElement) {
|
||||
const recordMsgOrNull = msg.records.find(
|
||||
record => element.replyElement!.sourceMsgIdInRecords === record.msgId
|
||||
);
|
||||
return `[回复消息 ${
|
||||
recordMsgOrNull &&
|
||||
recordMsgOrNull.peerUin != '284840486' // 非转发消息; 否则定位不到
|
||||
?
|
||||
rawMessageToText(recordMsgOrNull, recursiveLevel + 1) :
|
||||
`未找到消息记录 (MsgId = ${element.replyElement.sourceMsgIdInRecords})`
|
||||
}]`;
|
||||
}
|
||||
|
||||
if (element.picElement) {
|
||||
return `[图片 ${element.picElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.fileElement) {
|
||||
return `[文件 ${element.fileElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.videoElement) {
|
||||
return `[视频 ${element.videoElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.pttElement) {
|
||||
return `[语音 ${element.pttElement.duration}s]`;
|
||||
}
|
||||
|
||||
if (element.arkElement) {
|
||||
return `[卡片消息 ${element.arkElement.bytesData}]`;
|
||||
}
|
||||
|
||||
if (element.faceElement) {
|
||||
return `[表情 ${element.faceElement.faceText ?? ''}]`;
|
||||
}
|
||||
|
||||
if (element.marketFaceElement) {
|
||||
return `[商城表情 ${element.marketFaceElement.faceName}]`;
|
||||
}
|
||||
|
||||
if (element.markdownElement) {
|
||||
return `[Markdown ${element.markdownElement.content}]`;
|
||||
}
|
||||
|
||||
if (element.multiForwardMsgElement) {
|
||||
return `[转发消息]`;
|
||||
}
|
||||
|
||||
if (element.elementType === ElementType.GreyTip) {
|
||||
return `[灰条消息]`; // TODO: resolve the text
|
||||
}
|
||||
|
||||
return `[未实现 (ElementType = ${element.elementType})]`;
|
||||
}
|
||||
|
||||
for (const element of msg.elements) {
|
||||
tokens.push(msgElementToText(element));
|
||||
}
|
||||
|
||||
return tokens.join(' ');
|
||||
}
|
||||
|
@@ -54,21 +54,21 @@ export class NTQQFriendApi {
|
||||
uids.push(
|
||||
...buddyListV2.flatMap(item => {
|
||||
item.buddyUids.forEach(uid => {
|
||||
categoryMap.set(uid, { categoryId: item.categoryId, categroyName: item.categroyName });
|
||||
categoryMap.set(uid, { categoryId: item.categoryId, categoryName: item.categroyName });
|
||||
});
|
||||
return item.buddyUids;
|
||||
}));
|
||||
const data = await this.core.eventWrapper.callNoListenerEvent<NodeIKernelProfileService['getCoreAndBaseInfo']>(
|
||||
'NodeIKernelProfileService/getCoreAndBaseInfo', 5000, 'nodeStore', uids,
|
||||
);
|
||||
return Array.from(data).map(([key, value]) => {
|
||||
const category = categoryMap.get(key);
|
||||
return category ? {
|
||||
...value,
|
||||
categoryId: category.categoryId,
|
||||
categroyName: category.categroyName,
|
||||
} : value;
|
||||
});
|
||||
return buddyListV2.map(category => ({
|
||||
categoryId: category.categoryId,
|
||||
categorySortId: category.categorySortId,
|
||||
categoryName: category.categroyName,
|
||||
categoryMbCount: category.categroyMbCount,
|
||||
onlineCount: category.onlineCount,
|
||||
buddyList: category.buddyUids.map(uid => data.get(uid)!).filter(value => value),
|
||||
}));
|
||||
}
|
||||
|
||||
async isBuddy(uid: string) {
|
||||
|
@@ -296,7 +296,7 @@ export class NTQQMsgApi {
|
||||
if (!arkElement) {
|
||||
continue;
|
||||
}
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData);
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement?.bytesData || "");
|
||||
if (forwardData.app != 'com.tencent.multimsg') {
|
||||
continue;
|
||||
}
|
||||
|
@@ -231,7 +231,7 @@ export class NTQQUserApi {
|
||||
|
||||
//后期改成流水线处理
|
||||
async getUidByUinV2(Uin: string) {
|
||||
let uid = (await this.context.session.getProfileService().getUidByUinV2('FriendsServiceImpl', [Uin])).get(Uin);
|
||||
let uid = (await this.context.session.getProfileService().getUidByUin('FriendsServiceImpl', [Uin])).get(Uin);
|
||||
if (uid) return uid;
|
||||
uid = (await this.context.session.getGroupService().getUidByUins([Uin])).uids.get(Uin);
|
||||
if (uid) return uid;
|
||||
|
@@ -4,7 +4,7 @@ import fs from 'node:fs';
|
||||
import { InstanceContext } from './wrapper';
|
||||
import { proxiedListenerOf } from '@/common/utils/proxy-handler';
|
||||
import { GroupListener, MsgListener, ProfileListener } from './listeners';
|
||||
import { GroupMember, SelfInfo, SelfStatusInfo } from './entities';
|
||||
import { GroupMember, SelfInfo } from './entities';
|
||||
import { LegacyNTEventWrapper } from '@/common/framework/event-legacy';
|
||||
import { NTQQFileApi, NTQQFriendApi, NTQQGroupApi, NTQQMsgApi, NTQQSystemApi, NTQQUserApi, NTQQWebApi } from './apis';
|
||||
import os from 'node:os';
|
||||
@@ -90,8 +90,8 @@ export class NapCatCore {
|
||||
// Renamed from 'InitDataListener'
|
||||
async initNapCatCoreListeners() {
|
||||
const msgListener = new MsgListener();
|
||||
msgListener.onRecvMsg = (msg) => {
|
||||
//console.log('RecvMsg', msg);
|
||||
msgListener.onRecvMsg = (msgs) => {
|
||||
msgs.forEach(msg => this.context.logger.logMessage(msg, this.selfInfo));
|
||||
};
|
||||
//await sleep(2500);
|
||||
this.context.session.getMsgService().addKernelMsgListener(
|
||||
@@ -104,7 +104,7 @@ export class NapCatCore {
|
||||
Object.assign(this.selfInfo, profile);
|
||||
}
|
||||
};
|
||||
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
|
||||
profileListener.onSelfStatusChanged = (/* Info: SelfStatusInfo */) => {
|
||||
// if (Info.status == 20) {
|
||||
// log("账号状态变更为离线")
|
||||
// }
|
||||
@@ -128,12 +128,12 @@ export class NapCatCore {
|
||||
// 获取群成员
|
||||
}
|
||||
const sceneId = this.context.session.getGroupService().createMemberListScene(g.groupCode, 'groupMemberList_MainWindow');
|
||||
this.context.session.getGroupService().getNextMemberList(sceneId!, undefined, 3000).then(r => {
|
||||
this.context.session.getGroupService().getNextMemberList(sceneId!, undefined, 3000).then( /* r => {
|
||||
// console.log(`get group ${g.groupCode} members`, r);
|
||||
// r.result.infos.forEach(member => {
|
||||
// });
|
||||
// groupMembers.set(g.groupCode, r.result.infos);
|
||||
});
|
||||
} */);
|
||||
});
|
||||
};
|
||||
groupListener.onMemberListChange = (arg) => {
|
||||
|
@@ -26,36 +26,70 @@ export interface GetFileListParam {
|
||||
|
||||
export enum ElementType {
|
||||
UNKNOWN = 0,
|
||||
|
||||
TEXT = 1,
|
||||
|
||||
PIC = 2,
|
||||
|
||||
FILE = 3,
|
||||
|
||||
PTT = 4,
|
||||
|
||||
VIDEO = 5,
|
||||
|
||||
FACE = 6,
|
||||
|
||||
REPLY = 7,
|
||||
|
||||
WALLET = 9,
|
||||
GreyTip = 8,//Poke别叫戳一搓了 官方名字拍一拍 戳一戳是另一个名字
|
||||
|
||||
/**
|
||||
* “小灰条”,包括拍一拍 (Poke)、撤回提示等
|
||||
*/
|
||||
GreyTip = 8,
|
||||
|
||||
ARK = 10,
|
||||
|
||||
MFACE = 11,
|
||||
|
||||
LIVEGIFT = 12,
|
||||
|
||||
STRUCTLONGMSG = 13,
|
||||
|
||||
MARKDOWN = 14,
|
||||
|
||||
GIPHY = 15,
|
||||
|
||||
MULTIFORWARD = 16,
|
||||
|
||||
INLINEKEYBOARD = 17,
|
||||
|
||||
INTEXTGIFT = 18,
|
||||
|
||||
CALENDAR = 19,
|
||||
|
||||
YOLOGAMERESULT = 20,
|
||||
|
||||
AVRECORD = 21,
|
||||
|
||||
FEED = 22,
|
||||
|
||||
TOFURECORD = 23,
|
||||
|
||||
ACEBUBBLE = 24,
|
||||
|
||||
ACTIVITY = 25,
|
||||
|
||||
TOFU = 26,
|
||||
|
||||
FACEBUBBLE = 27,
|
||||
|
||||
SHARELOCATION = 28,
|
||||
|
||||
TASKTOPMSG = 29,
|
||||
|
||||
RECOMMENDEDMSG = 43,
|
||||
|
||||
ACTIONBAR = 44
|
||||
}
|
||||
|
||||
@@ -844,56 +878,142 @@ export enum NTSubMsgType {
|
||||
}
|
||||
export interface RawMessage {
|
||||
parentMsgPeer: Peer;
|
||||
parentMsgIdList: string[];
|
||||
id?: number;//扩展字段 用于处理OB11 ID
|
||||
guildId: string;
|
||||
msgRandom: string;
|
||||
|
||||
parentMsgIdList: string[];
|
||||
|
||||
/**
|
||||
* 扩展字段,与 Ob11 msg ID 有关
|
||||
*/
|
||||
id?: number;
|
||||
|
||||
guildId: string;
|
||||
|
||||
msgRandom: string;
|
||||
|
||||
msgId: string;
|
||||
|
||||
// 时间戳,秒
|
||||
/**
|
||||
* 消息时间戳(秒)
|
||||
*/
|
||||
msgTime: string;
|
||||
|
||||
msgSeq: string;
|
||||
|
||||
msgType: NTMsgType;
|
||||
|
||||
subMsgType: NTSubMsgType;
|
||||
|
||||
senderUid: string;
|
||||
senderUin: string; // 发送者QQ号
|
||||
peerUid: string; // 群号 或者 QQ uid
|
||||
peerUin: string; // 群号 或者 发送者QQ号
|
||||
|
||||
/**
|
||||
* 发送者 QQ 号
|
||||
*/
|
||||
senderUin: string;
|
||||
|
||||
/**
|
||||
* 群号 / 用户 UID
|
||||
*/
|
||||
peerUid: string;
|
||||
|
||||
/**
|
||||
* 群号 / 用户 QQ 号
|
||||
*/
|
||||
peerUin: string;
|
||||
|
||||
/**
|
||||
* 发送者昵称(如果是好友消息)
|
||||
*/
|
||||
sendNickName: string;
|
||||
sendMemberName?: string; // 发送者群名片
|
||||
|
||||
/**
|
||||
* 发送者群名片(如果是群消息)
|
||||
*/
|
||||
sendMemberName?: string;
|
||||
|
||||
chatType: ChatType;
|
||||
sendStatus?: number; // 消息状态,别人发的2是已撤回,自己发的2是已发送
|
||||
recallTime: string; // 撤回时间, "0"是没有撤回
|
||||
|
||||
/**
|
||||
* 消息状态,别人发的 2 是已撤回,自己发的 2 是已发送
|
||||
*/
|
||||
sendStatus?: number;
|
||||
|
||||
/**
|
||||
* 撤回时间,"0" 是没有撤回
|
||||
*/
|
||||
recallTime: string;
|
||||
|
||||
records: RawMessage[];
|
||||
elements: {
|
||||
elementId: string;
|
||||
elementType: ElementType;
|
||||
replyElement: {
|
||||
sourceMsgIdInRecords: string;
|
||||
senderUid: string; // 原消息发送者QQ号
|
||||
sourceMsgIsIncPic: boolean; // 原消息是否有图片
|
||||
sourceMsgText: string;
|
||||
replayMsgSeq: string; // 源消息的msgSeq,可以通过这个找到源消息的msgId
|
||||
};
|
||||
textElement: {
|
||||
atType: AtType;
|
||||
atUid: string; // QQ号
|
||||
content: string;
|
||||
atNtUid: string; // uid号
|
||||
};
|
||||
picElement: PicElement;
|
||||
pttElement: PttElement;
|
||||
arkElement: ArkElement;
|
||||
grayTipElement: GrayTipElement;
|
||||
faceElement: FaceElement;
|
||||
videoElement: VideoElement;
|
||||
fileElement: FileElement;
|
||||
marketFaceElement: MarketFaceElement;
|
||||
inlineKeyboardElement: InlineKeyboardElement;
|
||||
markdownElement: MarkdownElement;
|
||||
multiForwardMsgElement: MultiForwardMsgElement;
|
||||
}[];
|
||||
|
||||
elements: ElementWrapper[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 并非原生接口类型,故以 type 包装
|
||||
*/
|
||||
export type ElementWrapper = {
|
||||
elementId: string;
|
||||
|
||||
elementType: ElementType;
|
||||
|
||||
replyElement?: {
|
||||
sourceMsgIdInRecords: string;
|
||||
|
||||
/**
|
||||
* 源消息发送者 QQ 号
|
||||
*/
|
||||
senderUid: string;
|
||||
|
||||
/**
|
||||
* 源消息是否有图片
|
||||
*/
|
||||
sourceMsgIsIncPic: boolean;
|
||||
|
||||
/**
|
||||
* 源消息文本
|
||||
*/
|
||||
sourceMsgText: string;
|
||||
|
||||
/**
|
||||
* 源消息的 msgSeq,可以通过这个找到源消息的 msgId
|
||||
*/
|
||||
replayMsgSeq: string;
|
||||
};
|
||||
|
||||
textElement?: {
|
||||
atType: AtType;
|
||||
|
||||
/**
|
||||
* 被 @ 的 QQ 号
|
||||
*/
|
||||
atUid: string;
|
||||
|
||||
content: string;
|
||||
|
||||
/**
|
||||
* 被 @ 的 UID(从这里可以看出来 UID 的概念是 NT 才引入的)
|
||||
*/
|
||||
atNtUid: string;
|
||||
};
|
||||
|
||||
picElement?: PicElement;
|
||||
|
||||
pttElement?: PttElement;
|
||||
|
||||
arkElement?: ArkElement;
|
||||
|
||||
grayTipElement?: GrayTipElement;
|
||||
|
||||
faceElement?: FaceElement;
|
||||
|
||||
videoElement?: VideoElement;
|
||||
|
||||
fileElement?: FileElement;
|
||||
|
||||
marketFaceElement?: MarketFaceElement;
|
||||
|
||||
inlineKeyboardElement?: InlineKeyboardElement;
|
||||
|
||||
markdownElement?: MarkdownElement;
|
||||
|
||||
multiForwardMsgElement?: MultiForwardMsgElement;
|
||||
}
|
||||
|
@@ -176,10 +176,7 @@ export interface SimpleInfo {
|
||||
intimate: any | null;
|
||||
}
|
||||
|
||||
export interface FriendV2 extends SimpleInfo {
|
||||
categoryId?: number;
|
||||
categroyName?: string;
|
||||
}
|
||||
export type FriendV2 = SimpleInfo;
|
||||
|
||||
export interface SelfStatusInfo {
|
||||
uid: string;
|
||||
|
@@ -18,7 +18,7 @@ export enum ProfileBizType {
|
||||
|
||||
export interface NodeIKernelProfileService {
|
||||
|
||||
getUidByUinV2(callfrom: string, uin: Array<string>): Promise<Map<string, string>>;//uin->uid
|
||||
getUidByUin(callfrom: string, uin: Array<string>): Promise<Map<string, string>>;//uin->uid
|
||||
|
||||
getUinByUid(callfrom: string, uid: Array<string>): Promise<Map<string, string>>;
|
||||
|
||||
|
@@ -87,13 +87,12 @@ function pollForNTInitializationCheck() {
|
||||
try {
|
||||
if (ntIsInitialized_Internal()) {
|
||||
isSolve = true;
|
||||
clearInterval(intervalRef);
|
||||
resolve(true);
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
} finally {
|
||||
clearInterval(intervalRef);
|
||||
}
|
||||
}
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
@@ -113,7 +112,7 @@ async function fetchServices(timeout = 10000) {
|
||||
}),
|
||||
]).then(result => result ?
|
||||
{ wrapperSession, wrapperNodeApi, wrapperLoginService } :
|
||||
Promise.reject(),
|
||||
Promise.reject("fetchServices Timeout!"),
|
||||
);
|
||||
}
|
||||
let getWebUiUrlFunc = undefined;
|
||||
|
@@ -8,7 +8,10 @@ export class GetFriendWithCategory extends BaseAction<void, any> {
|
||||
async _handle(payload: void) {
|
||||
if (this.CoreContext.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
|
||||
//全新逻辑
|
||||
return OB11Constructor.friendsV2(await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true));
|
||||
return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({
|
||||
...category,
|
||||
buddyList: OB11Constructor.friendsV2(category.buddyList),
|
||||
}));
|
||||
} else {
|
||||
throw new Error('this ntqq version not support, must be 26702 or later');
|
||||
}
|
||||
|
@@ -39,15 +39,16 @@ export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
|
||||
throw Error('找不到相关的聊天记录' + data?.errMsg);
|
||||
}
|
||||
const msgList = data.msgList;
|
||||
const messages = await Promise.all(msgList.map(async msg => {
|
||||
const messages = (await Promise.all(msgList.map(async msg => {
|
||||
const resMsg = await OB11Constructor.message(this.CoreContext, msg, 'array');
|
||||
if (!resMsg) return;
|
||||
resMsg.message_id = MessageUnique.createMsg({
|
||||
guildId: '',
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
}, msg.msgId)!;
|
||||
return resMsg;
|
||||
}));
|
||||
}))).filter(msg => !!msg);
|
||||
messages.map(msg => {
|
||||
(<OB11ForwardMessage>msg).content = msg.message;
|
||||
delete (<any>msg).message;
|
||||
|
@@ -53,7 +53,7 @@ export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
|
||||
msg.id = MessageUnique.createMsg({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
|
||||
}));
|
||||
//转换消息
|
||||
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')));
|
||||
const ob11MsgList = (await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')))).filter(msg => !!msg);
|
||||
return { 'messages': ob11MsgList };
|
||||
}
|
||||
}
|
||||
|
@@ -48,7 +48,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Resp
|
||||
}));
|
||||
|
||||
//转换消息
|
||||
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')));
|
||||
const ob11MsgList = (await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')))).filter(msg => !!msg);
|
||||
return { 'messages': ob11MsgList };
|
||||
}
|
||||
}
|
||||
|
@@ -69,7 +69,7 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Mlikiowa V2.0.1 Refactor Todo
|
||||
// Mlikiowa V2.0.12 Refactor Todo
|
||||
// retMember.last_sent_time = parseInt((await getGroupMember(payload.group_id.toString(), retMember.user_id))?.lastSpeakTime || date.toString());
|
||||
// retMember.join_time = parseInt((await getGroupMember(payload.group_id.toString(), retMember.user_id))?.joinTime || date.toString());
|
||||
}
|
||||
|
@@ -83,7 +83,7 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Mlikiowa V2.0.1 Refactor Todo
|
||||
// Mlikiowa V2.0.12 Refactor Todo
|
||||
// _groupMembers.forEach(async item => {
|
||||
// item.last_sent_time = parseInt((await getGroupMember(payload.group_id.toString(), item.user_id))?.lastSpeakTime || date.toString());
|
||||
// item.join_time = parseInt((await getGroupMember(payload.group_id.toString(), item.user_id))?.joinTime || date.toString());
|
||||
|
@@ -44,7 +44,7 @@ class DeleteMsg extends BaseAction<Payload, void> {
|
||||
await NTQQMsgApi.recallMsg(msg.Peer, [msg.MsgId]);
|
||||
const data = await ret;
|
||||
if (!data) {
|
||||
throw new Error('Recall failed');
|
||||
//throw new Error('Recall failed');
|
||||
}
|
||||
//await sleep(100);
|
||||
//await NTQQMsgApi.getMsgsByMsgId(msg.Peer, [msg.MsgId]);
|
||||
|
@@ -38,6 +38,7 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
|
||||
peer,
|
||||
[msgIdWithPeer?.MsgId || payload.message_id.toString()]);
|
||||
const retMsg = await OB11Constructor.message(this.CoreContext, msg.msgList[0], 'array');
|
||||
if(!retMsg) throw Error('消息为空');
|
||||
try {
|
||||
retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!;
|
||||
retMsg.message_seq = retMsg.message_id;
|
||||
|
@@ -56,7 +56,7 @@ const _handlers: {
|
||||
if (atQQ === 'all') return SendMsgElementConstructor.at(coreContext, atQQ, atQQ, AtType.atAll, '全体成员');
|
||||
|
||||
// then the qq is a group member
|
||||
// Mlikiowa V2.0.1 Refactor Todo
|
||||
// Mlikiowa V2.0.12 Refactor Todo
|
||||
const uid = await coreContext.apis.UserApi.getUidByUinV2(atQQ);
|
||||
if (!uid) throw new Error('Get Uid Error');
|
||||
return SendMsgElementConstructor.at(coreContext, atQQ, uid, AtType.atUser, '');
|
||||
@@ -161,7 +161,7 @@ const _handlers: {
|
||||
} else {
|
||||
postData = data;
|
||||
}
|
||||
// Mlikiowa V2.0.1 Refactor Todo
|
||||
// Mlikiowa V2.0.12 Refactor Todo
|
||||
const signUrl = obContext.configLoader.configData.musicSignUrl;
|
||||
if (!signUrl) {
|
||||
if (data.type === 'qq') {
|
||||
|
@@ -105,6 +105,7 @@ async function createContext(coreContext: NapCatCore, payload: OB11PostSendMsg,
|
||||
return {
|
||||
chatType: isBuddy ? ChatType.friend : ChatType.temp,
|
||||
peerUid: Uid!,
|
||||
guildId: payload.group_id?.toString() || '',
|
||||
};
|
||||
}
|
||||
throw '请指定 group_id 或 user_id';
|
||||
|
@@ -43,9 +43,11 @@ import { OB11GroupEssenceEvent } from '../event/notice/OB11GroupEssenceEvent';
|
||||
import { MessageUnique } from '@/common/utils/MessageUnique';
|
||||
import { NapCatCore } from '@/core';
|
||||
|
||||
|
||||
export class OB11Constructor {
|
||||
static async message(core: NapCatCore, msg: RawMessage, messagePostFormat: any): Promise<OB11Message> {
|
||||
static async message(core: NapCatCore, msg: RawMessage, messagePostFormat: any): Promise<OB11Message | undefined> {
|
||||
if (msg.senderUin == "0") return;
|
||||
if (msg.peerUin == "0") return;
|
||||
//跳过空消息
|
||||
const NTQQGroupApi = core.apis.GroupApi;
|
||||
const NTQQUserApi = core.apis.UserApi;
|
||||
const NTQQFileApi = core.apis.FileApi;
|
||||
@@ -75,8 +77,8 @@ export class OB11Constructor {
|
||||
resMsg.sub_type = 'normal'; // 这里go-cqhttp是group,而onebot11标准是normal, 蛋疼
|
||||
resMsg.group_id = parseInt(msg.peerUin);
|
||||
//直接去QQNative取
|
||||
const memberList = await NTQQGroupApi.getGroupMembers(msg.peerUin);
|
||||
const member = memberList.get(msg.senderUin!);
|
||||
let member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
|
||||
if (!member) member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
|
||||
if (member) {
|
||||
resMsg.sender.role = OB11Constructor.groupMemberRole(member.role);
|
||||
resMsg.sender.nickname = member.nick;
|
||||
@@ -141,7 +143,7 @@ export class OB11Constructor {
|
||||
message_data['type'] = OB11MessageDataType.reply;
|
||||
//log("收到回复消息", element.replyElement);
|
||||
try {
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element.replyElement.sourceMsgIdInRecords);
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.replyElement?.sourceMsgIdInRecords);
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
@@ -278,13 +280,13 @@ export class OB11Constructor {
|
||||
chatType: msg.chatType,
|
||||
guildId: '',
|
||||
},
|
||||
msg.msgId,
|
||||
msg.msgSeq,
|
||||
msg.senderUid,
|
||||
element.elementId,
|
||||
element.elementType.toString(),
|
||||
element.pttElement.fileSize || '0',
|
||||
element.pttElement.fileUuid || '',
|
||||
msg.msgId,
|
||||
msg.msgSeq,
|
||||
msg.senderUid,
|
||||
element.elementId,
|
||||
element.elementType.toString(),
|
||||
element.pttElement.fileSize || '0',
|
||||
element.pttElement.fileUuid || '',
|
||||
);
|
||||
//以uuid作为文件名
|
||||
} else if (element.arkElement) {
|
||||
@@ -343,6 +345,7 @@ export class OB11Constructor {
|
||||
MultiMsg.parentMsgIdList = msg.parentMsgIdList;
|
||||
MultiMsg.id = MessageUnique.createMsg(ParentMsgPeer, MultiMsg.msgId);//该ID仅用查看 无法调用
|
||||
const msgList = await OB11Constructor.message(core, MultiMsg, 'array');
|
||||
if (!msgList) continue;
|
||||
message_data['data']['content'].push(msgList);
|
||||
//console.log("合并消息", msgList);
|
||||
}
|
||||
@@ -408,7 +411,7 @@ export class OB11Constructor {
|
||||
return;
|
||||
}
|
||||
//log("group msg", msg);
|
||||
// Mlikiowa V2.0.1 Refactor Todo
|
||||
// Mlikiowa V2.0.12 Refactor Todo
|
||||
// if (msg.senderUin && msg.senderUin !== '0') {
|
||||
// const member = await getGroupMember(msg.peerUid, msg.senderUin);
|
||||
// if (member && member.cardName !== msg.sendMemberName) {
|
||||
@@ -656,8 +659,6 @@ export class OB11Constructor {
|
||||
remark: friend.coreInfo.nick,
|
||||
sex: sexValue,
|
||||
level: 0,
|
||||
categroyName: friend.categroyName,
|
||||
categoryId: friend.categoryId,
|
||||
});
|
||||
});
|
||||
return data;
|
||||
|
@@ -1,86 +0,0 @@
|
||||
import { Group, NapCatCore } from '@/core';
|
||||
import { OB11Message } from '@/onebot/types';
|
||||
import chalk from 'chalk';
|
||||
|
||||
const spSegColor = chalk.blue;// for special segment
|
||||
const spColor = chalk.cyan;// for special
|
||||
|
||||
// todo: 应该放到core去用RawMessage解析打印
|
||||
export async function logOB11Message(coreContext: NapCatCore, ob11Message: OB11Message) {
|
||||
const isSelfSent = ob11Message.sender.user_id.toString() === coreContext.selfInfo.uin;
|
||||
let prefix = '';
|
||||
let group: Group | undefined;
|
||||
if (isSelfSent) {
|
||||
prefix = '发送消息 ';
|
||||
if (ob11Message.message_type === 'private') {
|
||||
prefix += '给私聊 ';
|
||||
prefix += `${ob11Message.target_id}`;
|
||||
} else {
|
||||
prefix += '给群聊 ';
|
||||
}
|
||||
}
|
||||
if (ob11Message.message_type === 'group') {
|
||||
if (ob11Message.group_id == 284840486) {
|
||||
// group = await coreContext.ApiContext.GroupApi.getGroup(ob11Message.group_id!.toString());
|
||||
prefix += '转发消息[外部来源] ';
|
||||
} else {
|
||||
group = await coreContext.apis.GroupApi.getGroup(ob11Message.group_id!.toString());
|
||||
prefix += `群[${group?.groupName}(${ob11Message.group_id})] `;
|
||||
}
|
||||
}
|
||||
let msgChain: string;
|
||||
if (Array.isArray(ob11Message.message)) {
|
||||
const msgParts = [];
|
||||
for (const segment of ob11Message.message) {
|
||||
if (segment.type === 'text') {
|
||||
msgParts.push(segment.data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
const groupMember = await coreContext.apis.GroupApi.getGroupMember(ob11Message.group_id!, segment.data.qq!);
|
||||
msgParts.push(spSegColor(`[@${groupMember?.cardName || groupMember?.nick}(${segment.data.qq})]`));
|
||||
} else if (segment.type === 'reply') {
|
||||
msgParts.push(spSegColor(`[回复消息|id:${segment.data.id}]`));
|
||||
} else if (segment.type === 'image') {
|
||||
msgParts.push(spSegColor(`[图片|${segment.data.url}]`));
|
||||
} else if (segment.type === 'face') {
|
||||
msgParts.push(spSegColor(`[表情|id:${segment.data.id}]`));
|
||||
} else if (segment.type === 'mface') {
|
||||
// @ts-expect-error 商城表情 url
|
||||
msgParts.push(spSegColor(`[商城表情|${segment.data.url}]`));
|
||||
} else if (segment.type === 'record') {
|
||||
msgParts.push(spSegColor(`[语音|${segment.data.file}]`));
|
||||
} else if (segment.type === 'file') {
|
||||
msgParts.push(spSegColor(`[文件|${segment.data.file}]`));
|
||||
} else if (segment.type === 'json') {
|
||||
msgParts.push(spSegColor(`[json|${JSON.stringify(segment.data)}]`));
|
||||
} else if (segment.type === 'markdown') {
|
||||
msgParts.push(spSegColor(`[markdown|${segment.data.content}]`));
|
||||
} else if (segment.type === 'video') {
|
||||
msgParts.push(spSegColor(`[视频|${segment.data.url}]`));
|
||||
} else if (segment.type === 'forward') {
|
||||
msgParts.push(spSegColor(`[转发|${segment.data.id}|消息开始]`));
|
||||
segment.data.content.forEach((msg) => {
|
||||
logOB11Message(coreContext, msg);
|
||||
});
|
||||
msgParts.push(spSegColor(`[转发|${segment.data.id}|消息结束]`));
|
||||
} else {
|
||||
msgParts.push(spSegColor(`[未实现|${JSON.stringify(segment)}]`));
|
||||
}
|
||||
}
|
||||
msgChain = msgParts.join(' ');
|
||||
} else {
|
||||
msgChain = ob11Message.message;
|
||||
}
|
||||
let msgString = `${prefix}${ob11Message.sender.nickname}(${ob11Message.sender.user_id}): ${msgChain}`;
|
||||
if (isSelfSent) {
|
||||
msgString = `${prefix}: ${msgChain}`;
|
||||
}
|
||||
coreContext.context.logger.log(msgString);
|
||||
}
|
||||
|
||||
export async function logOB11Notice(coreContext: NapCatCore, ob11Notice: any) {
|
||||
coreContext.context.logger.log(spColor('[Notice]'), ob11Notice);
|
||||
}
|
||||
|
||||
export async function logOB11Request(coreContext: NapCatCore, ob11Request: any) {
|
||||
coreContext.context.logger.log(spColor('[Request]'), ob11Request);
|
||||
}
|
@@ -25,7 +25,6 @@ import { WebUiDataRuntime } from '@/webui/src/helper/Data';
|
||||
import { OB11InputStatusEvent } from '@/onebot/event/notice/OB11InputStatusEvent';
|
||||
import { MessageUnique } from '@/common/utils/MessageUnique';
|
||||
import { OB11Constructor } from '@/onebot/helper/data';
|
||||
import { logOB11Message } from '@/onebot/helper/log';
|
||||
import { proxiedListenerOf } from '@/common/utils/proxy-handler';
|
||||
import { OB11FriendRequestEvent } from '@/onebot/event/request/OB11FriendRequest';
|
||||
import { OB11GroupAdminNoticeEvent } from '@/onebot/event/notice/OB11GroupAdminNoticeEvent';
|
||||
@@ -33,6 +32,7 @@ import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '@/onebot/event/not
|
||||
import { OB11GroupRequestEvent } from '@/onebot/event/request/OB11GroupRequest';
|
||||
import { OB11FriendRecallNoticeEvent } from '@/onebot/event/notice/OB11FriendRecallNoticeEvent';
|
||||
import { OB11GroupRecallNoticeEvent } from '@/onebot/event/notice/OB11GroupRecallNoticeEvent';
|
||||
import { LRUCache } from '@/common/utils/LRU';
|
||||
|
||||
//OneBot实现类
|
||||
export class NapCatOneBot11Adapter {
|
||||
@@ -87,7 +87,7 @@ export class NapCatOneBot11Adapter {
|
||||
if (ob11Config.http.enablePost) {
|
||||
ob11Config.http.postUrls.forEach(url => {
|
||||
this.networkManager.registerAdapter(new OB11ActiveHttpAdapter(
|
||||
url, ob11Config.token, this.core
|
||||
url, ob11Config.token, this.core, this
|
||||
));
|
||||
});
|
||||
}
|
||||
@@ -116,7 +116,7 @@ export class NapCatOneBot11Adapter {
|
||||
await WebUiDataRuntime.setOnOB11ConfigChanged(async (newConfig: OB11Config) => {
|
||||
const prev = this.configLoader.configData;
|
||||
this.configLoader.save(newConfig);
|
||||
this.context.logger.log(`OneBot11 配置更改:${JSON.stringify(prev)} -> ${JSON.stringify(newConfig)}`)
|
||||
this.context.logger.log(`OneBot11 配置更改:${JSON.stringify(prev)} -> ${JSON.stringify(newConfig)}`);
|
||||
await this.reloadNetwork(prev, newConfig);
|
||||
});
|
||||
}
|
||||
@@ -145,7 +145,7 @@ export class NapCatOneBot11Adapter {
|
||||
if (now.http.enablePost) {
|
||||
now.http.postUrls.forEach(url => {
|
||||
this.networkManager.registerAdapterAndOpen(new OB11ActiveHttpAdapter(
|
||||
url, now.token, this.core
|
||||
url, now.token, this.core, this
|
||||
));
|
||||
});
|
||||
} else {
|
||||
@@ -159,7 +159,7 @@ export class NapCatOneBot11Adapter {
|
||||
);
|
||||
for (const url of added) {
|
||||
await this.networkManager.registerAdapterAndOpen(new OB11ActiveHttpAdapter(
|
||||
url, now.token, this.core
|
||||
url, now.token, this.core, this
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -215,7 +215,6 @@ export class NapCatOneBot11Adapter {
|
||||
|
||||
private initMsgListener() {
|
||||
const msgListener = new MsgListener();
|
||||
|
||||
msgListener.onInputStatusPush = async data => {
|
||||
const uin = await this.core.apis.UserApi.getUinByUidV2(data.fromUin);
|
||||
this.context.logger.log(`[Notice] [输入状态] ${uin} ${data.statusText}`);
|
||||
@@ -245,16 +244,18 @@ export class NapCatOneBot11Adapter {
|
||||
.catch(e => this.context.logger.logError('处理消息失败', e));
|
||||
}
|
||||
};
|
||||
|
||||
const msgIdSend = new LRUCache<string, boolean>(100);
|
||||
msgListener.onMsgInfoListUpdate = async msgList => {
|
||||
this.emitRecallMsg(msgList)
|
||||
.catch(e => this.context.logger.logError('处理消息失败', e));
|
||||
|
||||
for (const msg of msgList.filter(e => e.senderUin == this.core.selfInfo.uin)) {
|
||||
// console.log(msg);
|
||||
if (msg.sendStatus == 2) {
|
||||
if (msg.sendStatus == 2 && !msgIdSend.get(msg.msgId)) {
|
||||
msgIdSend.put(msg.msgId, true);
|
||||
// 完成后再post
|
||||
OB11Constructor.message(this.core, msg, this.configLoader.configData.messagePostFormat)
|
||||
.then((ob11Msg) => {
|
||||
if(!ob11Msg) return;
|
||||
ob11Msg.target_id = parseInt(msg.peerUin);
|
||||
if (this.configLoader.configData.reportSelfMessage) {
|
||||
msg.id = MessageUnique.createMsg({
|
||||
@@ -264,7 +265,7 @@ export class NapCatOneBot11Adapter {
|
||||
}, msg.msgId);
|
||||
this.emitMsg(msg);
|
||||
} else {
|
||||
logOB11Message(this.core, ob11Msg);
|
||||
// logOB11Message(this.core, ob11Msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -423,9 +424,10 @@ export class NapCatOneBot11Adapter {
|
||||
|
||||
private async emitMsg(message: RawMessage) {
|
||||
const { debug, reportSelfMessage, messagePostFormat } = this.configLoader.configData;
|
||||
this.context.logger.logDebug('收到新消息', message);
|
||||
this.context.logger.logDebug('收到新消息 RawMessage', message);
|
||||
OB11Constructor.message(this.core, message, messagePostFormat).then((ob11Msg) => {
|
||||
this.context.logger.logDebug('收到消息: ', ob11Msg);
|
||||
if(!ob11Msg) return;
|
||||
this.context.logger.logDebug('转化为 OB11Message', ob11Msg);
|
||||
if (debug) {
|
||||
ob11Msg.raw = message;
|
||||
} else {
|
||||
@@ -433,8 +435,8 @@ export class NapCatOneBot11Adapter {
|
||||
return;
|
||||
}
|
||||
}
|
||||
logOB11Message(this.core, ob11Msg)
|
||||
.catch(e => this.context.logger.logError('logMessage error: ', e));
|
||||
// logOB11Message(this.core, ob11Msg)
|
||||
// .catch(e => this.context.logger.logError('logMessage error: ', e));
|
||||
const isSelfMsg = ob11Msg.user_id.toString() == this.core.selfInfo.uin;
|
||||
if (isSelfMsg && !reportSelfMessage) {
|
||||
return;
|
||||
@@ -481,6 +483,7 @@ export class NapCatOneBot11Adapter {
|
||||
let operatorId = message.senderUin;
|
||||
for (const element of message.elements) {
|
||||
const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
|
||||
if(!operatorUid) return;
|
||||
const operator = await this.core.apis.GroupApi.getGroupMember(message.peerUin, operatorUid);
|
||||
operatorId = operator?.uin || message.senderUin;
|
||||
}
|
||||
|
@@ -6,6 +6,7 @@ import { ActionName } from '@/onebot/action/types';
|
||||
import { OB11Response } from '@/onebot/action/OB11Response';
|
||||
import { LogWrapper } from '@/common/utils/log';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
|
||||
|
||||
export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
isClosed: boolean = false;
|
||||
@@ -25,7 +26,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
|
||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
if (this.connection) {
|
||||
if (this.connection && this.connection.readyState === WebSocket.OPEN) {
|
||||
this.connection.send(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
@@ -76,14 +77,22 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
'User-Agent': 'OneBot/11',
|
||||
},
|
||||
|
||||
});
|
||||
this.connection.on('open', () => {
|
||||
try{
|
||||
this.connectEvent(this.coreContext);
|
||||
}catch(e){
|
||||
this.logger.logError('[OneBot] [WebSocket Client] 发送连接生命周期失败', e);
|
||||
}
|
||||
|
||||
});
|
||||
this.connection.on('message', (data) => {
|
||||
this.handleMessage(data);
|
||||
});
|
||||
this.connection.once('close', () => {
|
||||
if (!isClosedByError) {
|
||||
this.logger.logError(`反向WebSocket (${this.url}) 连接意外关闭`);
|
||||
this.logger.logError(`在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接意外关闭`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
if (!this.isClosed) {
|
||||
this.connection = null;
|
||||
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
|
||||
@@ -92,8 +101,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
});
|
||||
this.connection.on('error', (err) => {
|
||||
isClosedByError = true;
|
||||
this.logger.logError(`反向WebSocket (${this.url}) 连接错误`, err);
|
||||
this.logger.logError(`在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接错误`, err);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
if (!this.isClosed) {
|
||||
this.connection = null;
|
||||
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
|
||||
@@ -101,7 +110,13 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
connectEvent(core: NapCatCore) {
|
||||
try {
|
||||
this.checkStateAndReply<any>(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT));
|
||||
} catch (e) {
|
||||
this.logger.logError('[OneBot] [WebSocket Client] 发送生命周期失败', e);
|
||||
}
|
||||
}
|
||||
private async handleMessage(message: any) {
|
||||
let receiveData: { action: ActionName, params?: any, echo?: any } = { action: ActionName.Unknown, params: {} };
|
||||
let echo = undefined;
|
||||
@@ -109,7 +124,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
try {
|
||||
receiveData = JSON.parse(message.toString());
|
||||
echo = receiveData.echo;
|
||||
this.logger.logDebug('收到正向Websocket消息', receiveData);
|
||||
this.logger.logDebug('[OneBot] [WebSocket Client] 收到正向Websocket消息', receiveData);
|
||||
} catch (e) {
|
||||
this.checkStateAndReply<any>(OB11Response.error('json解析失败,请检查数据格式', 1400, echo));
|
||||
}
|
||||
|
@@ -11,6 +11,7 @@ import { LogWrapper } from '@/common/utils/log';
|
||||
import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent';
|
||||
import { IncomingMessage } from 'http';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
|
||||
|
||||
export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
wsServer: WebSocketServer;
|
||||
@@ -36,6 +37,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
|
||||
this.heartbeatInterval = heartbeatInterval;
|
||||
this.wsServer = new WebSocketServer({ port: port, host: ip });
|
||||
let core = coreContext;
|
||||
this.wsServer.on('connection', async (wsClient, wsReq) => {
|
||||
if (!this.isOpen) {
|
||||
wsClient.close();
|
||||
@@ -43,9 +45,8 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
//鉴权
|
||||
this.authorize(token, wsClient, wsReq);
|
||||
|
||||
this.connectEvent(core, wsClient);
|
||||
wsClient.on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Client Error:', err.message));
|
||||
|
||||
wsClient.on('message', (message) => {
|
||||
this.handleMessage(wsClient, message).then().catch(this.logger.logError);
|
||||
});
|
||||
@@ -62,6 +63,14 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
});
|
||||
}).on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Server Error:', err.message));
|
||||
}
|
||||
|
||||
connectEvent(core: NapCatCore, wsClient: WebSocket) {
|
||||
try {
|
||||
this.checkStateAndReply<any>(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT), wsClient);
|
||||
} catch (e) {
|
||||
this.logger.logError('[OneBot] [WebSocket Server] 发送生命周期失败', e);
|
||||
}
|
||||
}
|
||||
|
||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
this.wsClientsMutex.runExclusive(async () => {
|
||||
@@ -82,7 +91,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
const addressInfo = this.wsServer.address();
|
||||
this.logger.log('[OneBot] [WebSocket Server] Server Started', typeof (addressInfo) === 'string' ? addressInfo : addressInfo?.address + ':' + addressInfo?.port);
|
||||
|
||||
|
||||
this.isOpen = true;
|
||||
this.registerHeartBeat();
|
||||
}
|
||||
|
@@ -7,7 +7,7 @@ export interface OB11User {
|
||||
age?: number;
|
||||
qid?: string;
|
||||
login_days?: number;
|
||||
categroyName?: string;
|
||||
categoryName?: string;
|
||||
categoryId?: number;
|
||||
}
|
||||
|
||||
|
@@ -175,10 +175,10 @@ export async function NCoreInitShell() {
|
||||
.then(result => {
|
||||
if (result.loginErrorInfo.errMsg) {
|
||||
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
|
||||
reject();
|
||||
loginService.getQRCodePicture();
|
||||
}
|
||||
})
|
||||
.catch(e => reject(e));
|
||||
.catch();
|
||||
}, 1000);
|
||||
} else {
|
||||
logger.log('没有 -q 指令指定快速登录,或未曾登录过这个 QQ,将使用二维码登录方式');
|
||||
|
@@ -30,7 +30,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
SettingItem(
|
||||
'<span id="napcat-update-title">Napcat</span>',
|
||||
undefined,
|
||||
SettingButton('V2.0.1', 'napcat-update-button', 'secondary'),
|
||||
SettingButton('V2.0.12', 'napcat-update-button', 'secondary'),
|
||||
),
|
||||
]),
|
||||
SettingList([
|
||||
@@ -176,6 +176,16 @@ async function onSettingWindowCreated(view: Element) {
|
||||
),
|
||||
SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs'))
|
||||
]),
|
||||
SettingItem(
|
||||
'Telegram 群',
|
||||
'https://t.me/+nLZEnpne-pQ1OWFl',
|
||||
SettingButton('进去逛逛', 'open-telegram')
|
||||
),
|
||||
SettingItem(
|
||||
'QQ 群',
|
||||
'518662028',
|
||||
SettingButton('我要进去', 'open-qq-group')
|
||||
),
|
||||
'</div>',
|
||||
].join(''),
|
||||
'text/html',
|
||||
@@ -188,6 +198,12 @@ async function onSettingWindowCreated(view: Element) {
|
||||
doc.querySelector('#open-docs')?.addEventListener('click', () => {
|
||||
window.open('https://napneko.github.io/', '_blank');
|
||||
});
|
||||
doc.querySelector('#open-telegram')?.addEventListener('click', () => {
|
||||
window.open('https://t.me/+nLZEnpne-pQ1OWFl', '_blank');
|
||||
});
|
||||
doc.querySelector('#open-qq-group')?.addEventListener('click', () => {
|
||||
window.open('https://qm.qq.com/q/VfjAq5HIMS', '_blank');
|
||||
});
|
||||
// 生成反向地址列表
|
||||
const buildHostListItem = (
|
||||
type: string,
|
||||
|
@@ -164,7 +164,7 @@ async function onSettingWindowCreated(view) {
|
||||
SettingItem(
|
||||
'<span id="napcat-update-title">Napcat</span>',
|
||||
void 0,
|
||||
SettingButton("V2.0.1", "napcat-update-button", "secondary")
|
||||
SettingButton("V2.0.12", "napcat-update-button", "secondary")
|
||||
)
|
||||
]),
|
||||
SettingList([
|
||||
@@ -308,6 +308,16 @@ async function onSettingWindowCreated(view) {
|
||||
),
|
||||
SettingItem("NapCat 文档", "", SettingButton("看看文档", "open-docs"))
|
||||
]),
|
||||
SettingItem(
|
||||
"Telegram 群",
|
||||
"https://t.me/+nLZEnpne-pQ1OWFl",
|
||||
SettingButton("进去逛逛", "open-telegram")
|
||||
),
|
||||
SettingItem(
|
||||
"QQ 群",
|
||||
"518662028",
|
||||
SettingButton("我要进去", "open-qq-group")
|
||||
),
|
||||
"</div>"
|
||||
].join(""),
|
||||
"text/html"
|
||||
@@ -318,6 +328,12 @@ async function onSettingWindowCreated(view) {
|
||||
doc.querySelector("#open-docs")?.addEventListener("click", () => {
|
||||
window.open("https://napneko.github.io/", "_blank");
|
||||
});
|
||||
doc.querySelector("#open-telegram")?.addEventListener("click", () => {
|
||||
window.open("https://t.me/+nLZEnpne-pQ1OWFl", "_blank");
|
||||
});
|
||||
doc.querySelector("#open-qq-group")?.addEventListener("click", () => {
|
||||
window.open("https://qm.qq.com/q/VfjAq5HIMS", "_blank");
|
||||
});
|
||||
const buildHostListItem = (type, host, index, inputAttrs = {}) => {
|
||||
const dom = {
|
||||
container: document.createElement("setting-item"),
|
||||
|
Reference in New Issue
Block a user