Compare commits

...

88 Commits

Author SHA1 Message Date
手瓜一十雪
4ceb2a8669 release: 2.0.21 2024-08-15 09:35:38 +08:00
手瓜一十雪
c778d3b699 chore: 提高兼容性 2024-08-15 00:33:20 +08:00
手瓜一十雪
47eda9cdf2 chore: boolen值校验 2024-08-15 00:14:31 +08:00
手瓜一十雪
dcaec4d356 style: lint 2024-08-15 00:10:13 +08:00
手瓜一十雪
aee4f349c6 chore: 丢弃废弃代码 2024-08-15 00:06:41 +08:00
手瓜一十雪
daa2c39902 chore: 兼容性提高 2024-08-15 00:00:21 +08:00
手瓜一十雪
5770fc02a1 chore: extend get兼容 2024-08-14 23:56:45 +08:00
手瓜一十雪
47cafd295b chore: 清理无用代码 2024-08-14 23:46:17 +08:00
手瓜一十雪
3296f2daf8 chore: 弃用无用代码 2024-08-14 23:41:34 +08:00
手瓜一十雪
962616545c fix: 显示自身消息 2024-08-14 23:09:07 +08:00
手瓜一十雪
11ea92c078 chore: logger 2024-08-14 23:03:24 +08:00
Seijo Cecilia
1d64fa4817 Merge remote-tracking branch 'origin/main' 2024-08-14 22:04:38 +08:00
Seijo Cecilia
c46f2956c2 fix: plugin slug 2024-08-14 22:04:29 +08:00
Wesley F. Young
8f6d4298be Merge pull request #256 from canxin121/main
typo: OB11InputStatusEvent event_type
2024-08-14 21:44:21 +08:00
canxin121
3bce81326e typo: OB11InputStatusEvent event_type 2024-08-14 21:42:12 +08:00
Seijo Cecilia
2ae9f6d0fe docs: name, slug and description of plugin manifest 2024-08-14 20:11:06 +08:00
手瓜一十雪
9266828278 chore: logger 2024-08-14 19:42:22 +08:00
手瓜一十雪
a8a2ffc33e release: 2.0.20 2024-08-14 19:38:50 +08:00
手瓜一十雪
27c4543471 Merge pull request #254 from lgc2333/patch-1
fix at error
2024-08-14 19:13:48 +08:00
student_2333
50a02cb59e fix at error 2024-08-14 19:08:42 +08:00
手瓜一十雪
50579bb9e6 fix: 修复某个笨蛋写的 2024-08-14 10:46:59 +08:00
手瓜一十雪
50512ca63c Merge pull request #250 from cnxysoft/upmain
fix: 二维码登录
2024-08-14 10:42:46 +08:00
手瓜一十雪
8b3577b216 Merge pull request #249 from DiheChen/patch-1
🐛 generating QR code when quick login fails
2024-08-14 10:42:33 +08:00
Alen
7553aab932 fix: 二维码登录
修复在没找到登陆历史记录后不加载二维码的问题
2024-08-14 10:32:39 +08:00
DiheChen
5dacdcfe5e 🐛 generating QR code when quick login fails 2024-08-14 10:31:28 +08:00
手瓜一十雪
8645a412b7 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2024-08-14 09:35:14 +08:00
手瓜一十雪
acad07a588 release: 2.0.18 2024-08-14 09:33:52 +08:00
手瓜一十雪
51bbb480bb Merge pull request #248 from cnxysoft/upmain
fix: GetCookie容错
2024-08-14 01:41:38 +08:00
Alen
f0306cd10a fix: GetCookie容错
修改 API提交不可用域名或不含skey返回时的容错
2024-08-14 01:32:32 +08:00
手瓜一十雪
25253ad9e7 fix: 异常 2024-08-14 01:22:08 +08:00
手瓜一十雪
51f2fb8e8b release: 2.0.17 2024-08-14 00:57:09 +08:00
手瓜一十雪
9e8d650cbd chore: 提高对trss兼容性 2024-08-14 00:56:42 +08:00
手瓜一十雪
d222ccfa58 fix: GetGuildProfile 2024-08-14 00:54:14 +08:00
手瓜一十雪
9a05aaa906 chore: 兼容guild api 2024-08-14 00:53:52 +08:00
手瓜一十雪
00fdce8876 style&&chore: lint 2024-08-14 00:47:50 +08:00
手瓜一十雪
29b51adf7d style&&chore: 逐步清退老版本代码 2024-08-14 00:47:31 +08:00
手瓜一十雪
8e14b39969 release: 2.0.16 2024-08-14 00:38:04 +08:00
手瓜一十雪
d9fb4d6c4d release: 2.0.15 2024-08-13 23:49:05 +08:00
手瓜一十雪
fcf2f4c5f2 Merge pull request #246 from cnxysoft/upmain
BUG修复
2024-08-13 23:48:19 +08:00
Alen
4e97501690 BUG修复
1.修改快速登陆提示使其更易辨别失败原因
2.修复API: Get_Cookie执行错误的问题
2024-08-13 23:46:21 +08:00
手瓜一十雪
b0402391fb chore: link 2024-08-13 23:11:34 +08:00
手瓜一十雪
f05a862cf9 fix 2024-08-13 22:18:24 +08:00
手瓜一十雪
3ea92d57c2 chore: 排除空消息 2024-08-13 22:11:28 +08:00
手瓜一十雪
254b85fbd8 release: v2.0.14 2024-08-13 22:02:56 +08:00
手瓜一十雪
16371c0cc4 fix: 统一消息格式 2024-08-13 21:00:22 +08:00
手瓜一十雪
2256d67e2b release: 2.0.12 2024-08-13 19:34:33 +08:00
手瓜一十雪
0af0bdede6 build: 2.0.12 test 2024-08-13 19:33:29 +08:00
手瓜一十雪
379f31b9de Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2024-08-13 16:22:24 +08:00
手瓜一十雪
771a524734 add log 2024-08-13 16:21:59 +08:00
Wesley F. Young
560e18a610 fix: no longer require admin when running after initialization 2024-08-13 16:09:15 +08:00
手瓜一十雪
147bdfab95 Revert "fix: 框架启动概率性失败"
This reverts commit 9d92270931.
2024-08-13 15:14:42 +08:00
手瓜一十雪
36b1b0f663 release: 2.0.11 2024-08-13 14:53:18 +08:00
手瓜一十雪
91511e4c3f fix: 某个笨蛋弄错的地方 2024-08-13 14:52:51 +08:00
手瓜一十雪
6a72056b25 release: 2.0.10 2024-08-13 13:58:53 +08:00
手瓜一十雪
62e0c57a50 Merge pull request #243 from cnxysoft/upmain
fix: 框架启动概率性失败
2024-08-13 13:50:08 +08:00
Alen
9d92270931 fix: 框架启动概率性失败
修复框架启动有概率失败的问题
2024-08-13 13:37:19 +08:00
手瓜一十雪
f61321d5a6 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2024-08-13 13:09:16 +08:00
手瓜一十雪
08ab2f8649 chore: 切换为缓存实现 2024-08-13 13:09:14 +08:00
Wesley F. Young
82962c4b42 docs: copyright 2024-08-13 09:06:46 +08:00
Wesley F. Young
bd24e8a4ad docs: plugin description 2024-08-13 09:02:50 +08:00
手瓜一十雪
6224d9a292 fix: 不合格类型 2024-08-13 00:59:26 +08:00
手瓜一十雪
bbc58f3671 release v2.0.9 2024-08-13 00:53:21 +08:00
手瓜一十雪
fcd620283f fix: 处理边界条件 2024-08-13 00:48:51 +08:00
手瓜一十雪
a78def3d2d chore: 移除异常内容 2024-08-13 00:39:20 +08:00
手瓜一十雪
43e94a5db0 fix: 跳过空消息 2024-08-13 00:38:42 +08:00
手瓜一十雪
e77bcc1267 release: 2.0.8 2024-08-12 23:50:03 +08:00
手瓜一十雪
9b458958b8 Revert "try fix"
This reverts commit 35419ade29.
2024-08-12 23:03:58 +08:00
手瓜一十雪
35419ade29 try fix 2024-08-12 23:01:36 +08:00
手瓜一十雪
15bd2ee887 fix: 2.0.7 2024-08-12 20:51:17 +08:00
手瓜一十雪
9394bafa8e fix 2024-08-12 20:46:28 +08:00
手瓜一十雪
94150a0c48 Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2024-08-12 20:42:10 +08:00
手瓜一十雪
8955fdfc23 release: 2.0.7 2024-08-12 20:41:57 +08:00
手瓜一十雪
c13aa6a545 build: 快速登录修复 2024-08-12 20:34:34 +08:00
手瓜一十雪
c73b50bd4a fix 2024-08-12 20:28:25 +08:00
手瓜一十雪
0a17a38bf1 fix: renderer 2024-08-12 18:25:34 +08:00
手瓜一十雪
0f7bfe1d66 release: 2.0.6 2024-08-12 18:22:36 +08:00
手瓜一十雪
cf3f488663 release: new group 2024-08-12 18:22:06 +08:00
Wesley F. Young
5f536fdb73 Merge remote-tracking branch 'origin/main' 2024-08-12 17:53:45 +08:00
Wesley F. Young
99d0b13cce Merge remote-tracking branch 'origin/main'
# Conflicts:
#	src/onebot/index.ts
2024-08-12 17:53:16 +08:00
手瓜一十雪
b04937f012 chore: v2.0.5 2024-08-12 17:52:41 +08:00
Wesley F. Young
91c9b059cf feat: new message logging using raw msg object 2024-08-12 17:52:27 +08:00
手瓜一十雪
35cc643440 fix 2024-08-12 17:49:09 +08:00
Wesley F. Young
b23bb8c46a Merge remote-tracking branch 'origin/main' 2024-08-12 17:36:10 +08:00
手瓜一十雪
64fdf62c4b Merge branch 'main' of https://github.com/NapNeko/NapCatQQ 2024-08-12 17:17:00 +08:00
手瓜一十雪
1c8a808571 chore: 2.0.4 2024-08-12 17:16:41 +08:00
Version
d8f0295032 chore:version change 2024-08-12 09:15:06 +00:00
手瓜一十雪
d59771ac2f fix: error 2024-08-12 17:14:44 +08:00
Wesley F. Young
45df093fac docs: add correct comments on fields 2024-08-12 17:07:22 +08:00
65 changed files with 795 additions and 620 deletions

View File

@@ -19,16 +19,17 @@ NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现。
**首次使用**请务必前往[官方文档](https://napneko.github.io/)查看使用教程。 **首次使用**请务必前往[官方文档](https://napneko.github.io/)查看使用教程。
## 相关链接 ## 相关链接
[QQ Group](https://qm.qq.com/q/VfjAq5HIMS)
[Telegram Link](https://t.me/+nLZEnpne-pQ1OWFl) [Telegram Link](https://t.me/+nLZEnpne-pQ1OWFl)
## 附加协议
禁止未授权任何项目使用Core部分代码用于二次开发与分发
## 鸣谢名单 ## 鸣谢名单
感谢 [LLOneBot](https://github.com/LLOneBot/LLOneBot) 提供初始版本基础 感谢 [LLOneBot](https://github.com/LLOneBot/LLOneBot) 提供初始版本基础
感谢 [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 感谢 [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持
--- ---
**任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**
## 使用许可
任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**此外,禁止任何项目未经授权二次分发或基于 [core](./src/core) 部分代码开发。**

View File

@@ -1,10 +1,10 @@
{ {
"manifest_version": 4, "manifest_version": 4,
"type": "extension", "type": "extension",
"name": "NapCat", "name": "NapCatQQ",
"slug": "NapCat", "slug": "NapCat.Framework",
"description": "OneBot v11 protocol implementation with NapCat logic", "description": "高性能的 OneBot 11 协议实现",
"version": "2.0.2", "version": "2.0.21",
"icon": "./logo.png", "icon": "./logo.png",
"authors": [ "authors": [
{ {

View File

@@ -2,7 +2,7 @@
"name": "napcat", "name": "napcat",
"private": true, "private": true,
"type": "module", "type": "module",
"version": "2.0.2", "version": "2.0.21",
"scripts": { "scripts": {
"build:framework": "vite build --mode framework", "build:framework": "vite build --mode framework",
"build:shell": "vite build --mode shell", "build:shell": "vite build --mode shell",

77
script/BootWay05_init.bat Normal file
View 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
View 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 %*

View 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 %*

View File

@@ -2,7 +2,7 @@ import path, { dirname } from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import fs from 'fs'; import fs from 'fs';
export const napcat_version = '2.0.2'; export const napcat_version = '2.0.21';
export class NapCatPathWrapper { export class NapCatPathWrapper {
binaryPath: string; binaryPath: string;

View File

@@ -2,6 +2,7 @@ import log4js, { Configuration } from 'log4js';
import { truncateString } from '@/common/utils/helper'; import { truncateString } from '@/common/utils/helper';
import path from 'node:path'; import path from 'node:path';
import chalk from 'chalk'; import chalk from 'chalk';
import { AtType, ChatType, ElementType, ElementWrapper, RawMessage, SelfInfo } from '@/core';
export enum LogLevel { export enum LogLevel {
DEBUG = 'debug', DEBUG = 'debug',
@@ -135,4 +136,104 @@ export class LogWrapper {
logFatal(...args: any[]) { logFatal(...args: any[]) {
this._log(LogLevel.FATAL, ...args); 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(' ');
} }

View File

@@ -141,7 +141,7 @@ export class NTQQFileApi {
filePath: thumbPath, filePath: thumbPath,
}, },
); );
let msg = await this.core.apis.MsgApi.getMsgsByMsgId({ const msg = await this.core.apis.MsgApi.getMsgsByMsgId({
guildId: '', guildId: '',
chatType: chatType, chatType: chatType,
peerUid: peerUid, peerUid: peerUid,
@@ -150,13 +150,13 @@ export class NTQQFileApi {
return data[1].filePath; return data[1].filePath;
} }
//获取原始消息 //获取原始消息
let FileElements = msg?.msgList[0]?.elements?.find(e => e.elementId === elementId); const FileElements = msg?.msgList[0]?.elements?.find(e => e.elementId === elementId);
if (!FileElements) { if (!FileElements) {
//失败则就乱来 Todo //失败则就乱来 Todo
return data[1].filePath; return data[1].filePath;
} }
//从原始消息获取文件路径 //从原始消息获取文件路径
let filePath = const filePath =
FileElements?.fileElement?.filePath || FileElements?.fileElement?.filePath ||
FileElements?.pttElement?.filePath || FileElements?.pttElement?.filePath ||
FileElements?.videoElement?.filePath || FileElements?.videoElement?.filePath ||

View File

@@ -26,10 +26,6 @@ export class NTQQFriendApi {
return Array.from(data.values()); return Array.from(data.values());
} }
async getBuddyIdMapCache(refresh = false): Promise<LimitedHashTable<string, string>> {
return await this.getBuddyIdMap(refresh);
}
async getBuddyIdMap(refresh = false): Promise<LimitedHashTable<string, string>> { async getBuddyIdMap(refresh = false): Promise<LimitedHashTable<string, string>> {
const uids: string[] = []; const uids: string[] = [];
const retMap: LimitedHashTable<string, string> = new LimitedHashTable<string, string>(5000); const retMap: LimitedHashTable<string, string> = new LimitedHashTable<string, string>(5000);

View File

@@ -37,7 +37,6 @@ export class NTQQMsgApi {
emojiId = emojiId.toString(); emojiId = emojiId.toString();
return this.context.session.getMsgService().setMsgEmojiLikes(peer, msgSeq, emojiId, emojiId.length > 3 ? '2' : '1', set); return this.context.session.getMsgService().setMsgEmojiLikes(peer, msgSeq, emojiId, emojiId.length > 3 ? '2' : '1', set);
} }
async getMultiMsg(peer: Peer, rootMsgId: string, parentMsgId: string): Promise<GeneralCallResult & { async getMultiMsg(peer: Peer, rootMsgId: string, parentMsgId: string): Promise<GeneralCallResult & {
msgList: RawMessage[] msgList: RawMessage[]
} | undefined> { } | undefined> {
@@ -129,64 +128,9 @@ export class NTQQMsgApi {
peerUid: peer.peerUid, peerUid: peer.peerUid,
}, msgIds); }, msgIds);
} }
async sendMsgV2(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) {
function generateMsgId() {
const timestamp = Math.floor(Date.now() / 1000);
const random = Math.floor(Math.random() * Math.pow(2, 32));
const buffer = Buffer.alloc(8);
buffer.writeUInt32BE(timestamp, 0);
buffer.writeUInt32BE(random, 4);
const msgId = BigInt('0x' + buffer.toString('hex')).toString();
return msgId;
}
// 此处有采用Hack方法 利用数据返回正确得到对应消息
// 与之前 Peer队列 MsgSeq队列 真正的MsgId并发不同
// 谨慎采用 目前测试暂无问题 Developer.Mlikiowa
let msgId: string;
try {
msgId = await this.getMsgUnique(peer.chatType, await this.getServerTime());
} catch (error) {
//if (!napCatCore.session.getMsgService()['generateMsgUniqueId'])
//兜底识别策略V2
msgId = generateMsgId().toString();
}
const data = await this.core.eventWrapper.CallNormalEvent<
(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<any, any>) => Promise<unknown>,
(msgList: RawMessage[]) => void
>(
'NodeIKernelMsgService/sendMsg',
'NodeIKernelMsgListener/onMsgInfoListUpdate',
1,
timeout,
(msgRecords: RawMessage[]) => {
for (const msgRecord of msgRecords) {
if (msgRecord.msgId === msgId && msgRecord.sendStatus === 2) {
return true;
}
}
return false;
},
msgId,
peer,
msgElements,
new Map(),
);
const retMsg = data[1].find(msgRecord => {
if (msgRecord.msgId === msgId) {
return true;
}
});
return retMsg;
}
sendMsgEx(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) {
//return NTQQMsgApi.sendMsgV1(peer, msgElements, waitComplete, timeout);
}
async PrepareTempChat(toUserUid: string, GroupCode: string, nickname: string) { async PrepareTempChat(toUserUid: string, GroupCode: string, nickname: string) {
//By Jadx/Ida Mlikiowa //By Jadx/Ida Mlikiowa
let TempGameSession = { const TempGameSession = {
nickname: "", nickname: "",
gameAppId: "", gameAppId: "",
selfTinyId: "", selfTinyId: "",
@@ -210,12 +154,12 @@ export class NTQQMsgApi {
async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) { async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) {
//唉? !我有个想法 //唉? !我有个想法
if (peer.chatType === ChatType.temp && peer.guildId && peer.guildId !== '') { if (peer.chatType === ChatType.temp && peer.guildId && peer.guildId !== '') {
let member = await this.core.apis.GroupApi.getGroupMember(peer.guildId, peer.peerUid!); const member = await this.core.apis.GroupApi.getGroupMember(peer.guildId, peer.peerUid!);
if (member) { if (member) {
await this.PrepareTempChat(peer.peerUid, peer.guildId, member.nick); await this.PrepareTempChat(peer.peerUid, peer.guildId, member.nick);
} }
} }
const msgId = await this.getMsgUnique(peer.chatType, await this.getServerTime()); const msgId = await this.generateMsgUniqueId(peer.chatType, await this.getServerTime());
peer.guildId = msgId; peer.guildId = msgId;
const data = await this.core.eventWrapper.CallNormalEvent< const data = await this.core.eventWrapper.CallNormalEvent<
(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<any, any>) => Promise<unknown>, (msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<any, any>) => Promise<unknown>,
@@ -246,21 +190,14 @@ export class NTQQMsgApi {
return retMsg; return retMsg;
} }
async getMsgUnique(chatType: number, time: string) { async generateMsgUniqueId(chatType: number, time: string) {
if (this.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
return this.context.session.getMsgService().generateMsgUniqueId(chatType, time); return this.context.session.getMsgService().generateMsgUniqueId(chatType, time);
} }
return this.context.session.getMsgService().getMsgUniqueId(time);
}
async getServerTime() { async getServerTime() {
return this.context.session.getMSFService().getServerTime(); return this.context.session.getMSFService().getServerTime();
} }
async getServerTimeV2() {
return this.core.eventWrapper.callNoListenerEvent<() => string>('NodeIKernelMsgService/getServerTime', 5000);
}
async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) { async forwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
return this.context.session.getMsgService().forwardMsg(msgIds, srcPeer, [destPeer], new Map()); return this.context.session.getMsgService().forwardMsg(msgIds, srcPeer, [destPeer], new Map());
} }
@@ -296,7 +233,7 @@ export class NTQQMsgApi {
if (!arkElement) { if (!arkElement) {
continue; continue;
} }
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData); const forwardData: any = JSON.parse(arkElement.arkElement?.bytesData || "");
if (forwardData.app != 'com.tencent.multimsg') { if (forwardData.app != 'com.tencent.multimsg') {
continue; continue;
} }

View File

@@ -155,16 +155,10 @@ export class NTQQUserApi {
//需要异常处理 //需要异常处理
async getCookies(domain: string) { async getCookies(domain: string) {
const ClientKeyData = await this.forceFetchClientKey(); const ClientKeyData = await this.forceFetchClientKey();
const requestUrl = `https://ssl.ptlogin2.qq.com/jump?${ const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + this.core.selfInfo.uin +
new URLSearchParams({ '&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + this.core.selfInfo.uin + '%2Finfocenter&keyindex=19%27';
ptlang: '1033', const cookies: { [key: string]: string; } = await RequestUtil.HttpsGetCookies(requestUrl);
clientuin: this.core.selfInfo.uin, return cookies;
clientkey: ClientKeyData.clientKey,
u1: `https://user.qzone.qq.com/${this.core.selfInfo.uin}/infocenter`,
keyindex: '19',
})
}`;
return await RequestUtil.HttpsGetCookies(requestUrl);
} }
async getPSkey(domainList: string[]) { async getPSkey(domainList: string[]) {
@@ -209,39 +203,14 @@ export class NTQQUserApi {
return skey; return skey;
} }
/**
* @deprecated
*/
async getUidByUin(Uin: string) {
if (this.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
return await this.getUidByUinV2(Uin);
}
return await this.getUidByUinV1(Uin);
}
/**
* @deprecated
*/
async getUinByUid(Uid: string) {
if (this.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
return await this.getUinByUidV2(Uid);
}
return await this.getUinByUidV1(Uid);
}
//后期改成流水线处理 //后期改成流水线处理
async getUidByUinV2(Uin: string) { 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; if (uid) return uid;
uid = (await this.context.session.getGroupService().getUidByUins([Uin])).uids.get(Uin); uid = (await this.context.session.getGroupService().getUidByUins([Uin])).uids.get(Uin);
if (uid) return uid; if (uid) return uid;
uid = (await this.context.session.getUixConvertService().getUid([Uin])).uidInfo.get(Uin); uid = (await this.context.session.getUixConvertService().getUid([Uin])).uidInfo.get(Uin);
if (uid) return uid; if (uid) return uid;
// console.log((await this.core.getApiContext().FriendApi.getBuddyIdMapCache(true)));
uid = (await this.core.apis.FriendApi.getBuddyIdMapCache(true)).getValue(Uin);//从Buddy缓存获取Uid
if (uid) return uid;
uid = (await this.core.apis.FriendApi.getBuddyIdMap(true)).getValue(Uin);
if (uid) return uid;
const unveifyUid = (await this.getUserDetailInfoByUinV2(Uin)).detail.uid;//从QQ Native 特殊转换 const unveifyUid = (await this.getUserDetailInfoByUinV2(Uin)).detail.uid;//从QQ Native 特殊转换
if (unveifyUid.indexOf('*') == -1) uid = unveifyUid; if (unveifyUid.indexOf('*') == -1) uid = unveifyUid;
//if (uid) return uid; //if (uid) return uid;
@@ -256,44 +225,12 @@ export class NTQQUserApi {
if (uin) return uin; if (uin) return uin;
uin = (await this.context.session.getUixConvertService().getUin([Uid])).uinInfo.get(Uid); uin = (await this.context.session.getUixConvertService().getUin([Uid])).uinInfo.get(Uid);
if (uin) return uin; if (uin) return uin;
uin = (await this.core.apis.FriendApi.getBuddyIdMapCache(true)).getKey(Uid);//从Buddy缓存获取Uin
if (uin) return uin;
uin = (await this.core.apis.FriendApi.getBuddyIdMap(true)).getKey(Uid); uin = (await this.core.apis.FriendApi.getBuddyIdMap(true)).getKey(Uid);
if (uin) return uin; if (uin) return uin;
uin = (await this.getUserDetailInfo(Uid)).uin; //从QQ Native 转换 uin = (await this.getUserDetailInfo(Uid)).uin; //从QQ Native 转换
return uin; return uin;
} }
async getUidByUinV1(Uin: string) {
// 通用转换开始尝试
let uid = (await this.context.session.getUixConvertService().getUid([Uin])).uidInfo.get(Uin);
if (!uid) {
const unveifyUid = (await this.getUserDetailInfoByUin(Uin)).info.uid;//从QQ Native 特殊转换 方法三
if (unveifyUid.indexOf('*') == -1) {
uid = unveifyUid;
}
}
return uid;
}
async getUinByUidV1(Uid: string) {
const ret = await this.core.eventWrapper.callNoListenerEvent<(Uin: string[]) => Promise<{
uinInfo: Map<string, string>
}>>
('NodeIKernelUixConvertService/getUin', 5000, [Uid]);
let uin = ret.uinInfo.get(Uid);
if (!uin) {
uin = (await this.getUserDetailInfo(Uid)).uin; //从QQ Native 转换
}
// if (!uin) {
// uin = (await NTQQFriendApi.getFriends(false)).find((t) => { t.uid == Uid })?.uin; //从QQ Native 缓存转换
// }
// if (!uin) {
// uin = (await NTQQFriendApi.getFriends(true)).find((t) => { t.uid == Uid })?.uin; //从QQ Native 非缓存转换
// }
return uin;
}
async getRecentContactListSnapShot(count: number) { async getRecentContactListSnapShot(count: number) {
return await this.context.session.getRecentContactService().getRecentContactListSnapShot(count); return await this.context.session.getRecentContactService().getRecentContactListSnapShot(count);
} }

View File

@@ -4,7 +4,7 @@ import fs from 'node:fs';
import { InstanceContext } from './wrapper'; import { InstanceContext } from './wrapper';
import { proxiedListenerOf } from '@/common/utils/proxy-handler'; import { proxiedListenerOf } from '@/common/utils/proxy-handler';
import { GroupListener, MsgListener, ProfileListener } from './listeners'; 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 { LegacyNTEventWrapper } from '@/common/framework/event-legacy';
import { NTQQFileApi, NTQQFriendApi, NTQQGroupApi, NTQQMsgApi, NTQQSystemApi, NTQQUserApi, NTQQWebApi } from './apis'; import { NTQQFileApi, NTQQFriendApi, NTQQGroupApi, NTQQMsgApi, NTQQSystemApi, NTQQUserApi, NTQQWebApi } from './apis';
import os from 'node:os'; import os from 'node:os';
@@ -90,8 +90,11 @@ export class NapCatCore {
// Renamed from 'InitDataListener' // Renamed from 'InitDataListener'
async initNapCatCoreListeners() { async initNapCatCoreListeners() {
const msgListener = new MsgListener(); const msgListener = new MsgListener();
msgListener.onRecvMsg = (msg) => { msgListener.onRecvMsg = (msgs) => {
//console.log('RecvMsg', msg); msgs.forEach(msg => this.context.logger.logMessage(msg, this.selfInfo));
};
msgListener.onAddSendMsg = (msg) => {
this.context.logger.logMessage(msg, this.selfInfo);
}; };
//await sleep(2500); //await sleep(2500);
this.context.session.getMsgService().addKernelMsgListener( this.context.session.getMsgService().addKernelMsgListener(
@@ -104,7 +107,7 @@ export class NapCatCore {
Object.assign(this.selfInfo, profile); Object.assign(this.selfInfo, profile);
} }
}; };
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => { profileListener.onSelfStatusChanged = (/* Info: SelfStatusInfo */) => {
// if (Info.status == 20) { // if (Info.status == 20) {
// log("账号状态变更为离线") // log("账号状态变更为离线")
// } // }
@@ -128,12 +131,12 @@ export class NapCatCore {
// 获取群成员 // 获取群成员
} }
const sceneId = this.context.session.getGroupService().createMemberListScene(g.groupCode, 'groupMemberList_MainWindow'); 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); // console.log(`get group ${g.groupCode} members`, r);
// r.result.infos.forEach(member => { // r.result.infos.forEach(member => {
// }); // });
// groupMembers.set(g.groupCode, r.result.infos); // groupMembers.set(g.groupCode, r.result.infos);
}); } */);
}); });
}; };
groupListener.onMemberListChange = (arg) => { groupListener.onMemberListChange = (arg) => {

View File

@@ -26,36 +26,70 @@ export interface GetFileListParam {
export enum ElementType { export enum ElementType {
UNKNOWN = 0, UNKNOWN = 0,
TEXT = 1, TEXT = 1,
PIC = 2, PIC = 2,
FILE = 3, FILE = 3,
PTT = 4, PTT = 4,
VIDEO = 5, VIDEO = 5,
FACE = 6, FACE = 6,
REPLY = 7, REPLY = 7,
WALLET = 9, WALLET = 9,
GreyTip = 8,//Poke别叫戳一搓了 官方名字拍一拍 戳一戳是另一个名字
/**
* “小灰条”,包括拍一拍 (Poke)、撤回提示等
*/
GreyTip = 8,
ARK = 10, ARK = 10,
MFACE = 11, MFACE = 11,
LIVEGIFT = 12, LIVEGIFT = 12,
STRUCTLONGMSG = 13, STRUCTLONGMSG = 13,
MARKDOWN = 14, MARKDOWN = 14,
GIPHY = 15, GIPHY = 15,
MULTIFORWARD = 16, MULTIFORWARD = 16,
INLINEKEYBOARD = 17, INLINEKEYBOARD = 17,
INTEXTGIFT = 18, INTEXTGIFT = 18,
CALENDAR = 19, CALENDAR = 19,
YOLOGAMERESULT = 20, YOLOGAMERESULT = 20,
AVRECORD = 21, AVRECORD = 21,
FEED = 22, FEED = 22,
TOFURECORD = 23, TOFURECORD = 23,
ACEBUBBLE = 24, ACEBUBBLE = 24,
ACTIVITY = 25, ACTIVITY = 25,
TOFU = 26, TOFU = 26,
FACEBUBBLE = 27, FACEBUBBLE = 27,
SHARELOCATION = 28, SHARELOCATION = 28,
TASKTOPMSG = 29, TASKTOPMSG = 29,
RECOMMENDEDMSG = 43, RECOMMENDEDMSG = 43,
ACTIONBAR = 44 ACTIONBAR = 44
} }
@@ -844,56 +878,142 @@ export enum NTSubMsgType {
} }
export interface RawMessage { export interface RawMessage {
parentMsgPeer: Peer; 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; msgId: string;
// 时间戳,秒 /**
* 消息时间戳(秒)
*/
msgTime: string; msgTime: string;
msgSeq: string; msgSeq: string;
msgType: NTMsgType; msgType: NTMsgType;
subMsgType: NTSubMsgType; subMsgType: NTSubMsgType;
senderUid: string; senderUid: string;
senderUin: string; // 发送者QQ号
peerUid: string; // 群号 或者 QQ uid /**
peerUin: string; // 群号 或者 发送者QQ号 * 发送者 QQ
*/
senderUin: string;
/**
* 群号 / 用户 UID
*/
peerUid: string;
/**
* 群号 / 用户 QQ 号
*/
peerUin: string;
/**
* 发送者昵称(如果是好友消息)
*/
sendNickName: string; sendNickName: string;
sendMemberName?: string; // 发送者群名片
/**
* 发送者群名片(如果是群消息)
*/
sendMemberName?: string;
chatType: ChatType; chatType: ChatType;
sendStatus?: number; // 消息状态别人发的2是已撤回自己发的2是已发送
recallTime: string; // 撤回时间, "0"是没有撤回 /**
* 消息状态,别人发的 2 是已撤回,自己发的 2 是已发送
*/
sendStatus?: number;
/**
* 撤回时间,"0" 是没有撤回
*/
recallTime: string;
records: RawMessage[]; records: RawMessage[];
elements: {
elementId: string; elements: ElementWrapper[];
elementType: ElementType; }
replyElement: {
sourceMsgIdInRecords: string; /**
senderUid: string; // 原消息发送者QQ号 * 并非原生接口类型,故以 type 包装
sourceMsgIsIncPic: boolean; // 原消息是否有图片 */
sourceMsgText: string; export type ElementWrapper = {
replayMsgSeq: string; // 源消息的msgSeq可以通过这个找到源消息的msgId elementId: string;
};
textElement: { elementType: ElementType;
atType: AtType;
atUid: string; // QQ号 replyElement?: {
content: string; sourceMsgIdInRecords: string;
atNtUid: string; // uid号
}; /**
picElement: PicElement; * 源消息发送者 QQ 号
pttElement: PttElement; */
arkElement: ArkElement; senderUid: string;
grayTipElement: GrayTipElement;
faceElement: FaceElement; /**
videoElement: VideoElement; * 源消息是否有图片
fileElement: FileElement; */
marketFaceElement: MarketFaceElement; sourceMsgIsIncPic: boolean;
inlineKeyboardElement: InlineKeyboardElement;
markdownElement: MarkdownElement; /**
multiForwardMsgElement: MultiForwardMsgElement; * 源消息文本
}[]; */
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;
} }

View File

@@ -18,7 +18,7 @@ export enum ProfileBizType {
export interface NodeIKernelProfileService { 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>>; getUinByUid(callfrom: string, uid: Array<string>): Promise<Map<string, string>>;

View File

@@ -87,12 +87,11 @@ function pollForNTInitializationCheck() {
try { try {
if (ntIsInitialized_Internal()) { if (ntIsInitialized_Internal()) {
isSolve = true; isSolve = true;
clearInterval(intervalRef);
resolve(true); resolve(true);
} }
} catch (error) { } catch (error) {
reject(error); reject(error);
} finally {
clearInterval(intervalRef);
} }
}, 500); }, 500);
}); });
@@ -113,7 +112,7 @@ async function fetchServices(timeout = 10000) {
}), }),
]).then(result => result ? ]).then(result => result ?
{ wrapperSession, wrapperNodeApi, wrapperLoginService } : { wrapperSession, wrapperNodeApi, wrapperLoginService } :
Promise.reject(), Promise.reject("fetchServices Timeout!"),
); );
} }
let getWebUiUrlFunc = undefined; let getWebUiUrlFunc = undefined;

View File

@@ -13,7 +13,7 @@ import { NapCatOneBot11Adapter } from '@/onebot';
//Framework ES入口文件 //Framework ES入口文件
export async function getWebUiUrl() { export async function getWebUiUrl() {
let WebUiConfigData = (await WebUiConfig.GetWebUIConfig()); const WebUiConfigData = (await WebUiConfig.GetWebUIConfig());
return "http://127.0.0.1:" + WebUiConfigData.port + '/webui/?token=' + WebUiConfigData.token; return "http://127.0.0.1:" + WebUiConfigData.port + '/webui/?token=' + WebUiConfigData.token;
} }
export async function NCoreInitFramework( export async function NCoreInitFramework(

View File

@@ -1,14 +1,38 @@
export const onSettingWindowCreated = async (view) => { export const onSettingWindowCreated = async (view) => {
view.style.width = "100%";
view.style.height = "100%"; // view.style.width = "100%";
//添加iframe // view.style.height = "100%";
const iframe = document.createElement("iframe"); // //添加iframe
iframe.src = await window.napcat.getWebUiUrl(); // const iframe = document.createElement("iframe");
iframe.width = "100%"; // iframe.src = await window.napcat.getWebUiUrl();
iframe.height = "100%"; // iframe.width = "100%";
iframe.style.border = "none"; // iframe.height = "100%";
//去掉iframe滚动条 // iframe.style.border = "none";
//iframe.scrolling = "no"; // //去掉iframe滚动条
//有滚动条何尝不是一种美 // //iframe.scrolling = "no";
view.appendChild(iframe); // //有滚动条何尝不是一种美
// view.appendChild(iframe);
let webui = await window.napcat.getWebUiUrl();
let panel = `
<setting-section data-title="">
<setting-panel>
<setting-list data-direction="column">
<setting-item>
<setting-button data-type="primary" class="nc_openwebui">打开配置页面</setting-button>
</setting-item>
<setting-item>
<div>
<setting-text class="nc_webui">WebUi</setting-text>
</div>
</setting-item>
</setting-list>
</setting-panel>
</setting-section>
`;
view.innerHTML = panel;
view.querySelector(".nc_openwebui").addEventListener("click", () => {
window.open(webui, "_blank");
});
view.querySelector(".nc_webui").innerText = webui;
}; };

View File

@@ -5,7 +5,7 @@ import { ActionName } from '../types';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
count: { type: 'number' }, count: { type: ['number', 'string'] },
}, },
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -17,7 +17,7 @@ export class FetchCustomFace extends BaseAction<Payload, string[]> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
//48 可能正好是QQ需要的一个页面的数量 Tagged Mlikiowa //48 可能正好是QQ需要的一个页面的数量 Tagged Mlikiowa
const ret = await this.CoreContext.apis.MsgApi.fetchFavEmojiList(payload.count || 48); const ret = await this.CoreContext.apis.MsgApi.fetchFavEmojiList(parseInt((payload.count || '0').toString()) || 48);
return ret.emojiInfoList.map(e => e.url); return ret.emojiInfoList.map(e => e.url);
} }
} }

View File

@@ -12,7 +12,7 @@ const SchemaData = {
emojiId: { type: 'string' }, emojiId: { type: 'string' },
emojiType: { type: 'string' }, emojiType: { type: 'string' },
message_id: { type: ['string', 'number'] }, message_id: { type: ['string', 'number'] },
count: { type: 'number' }, count: { type: ['string', 'number'] },
}, },
required: ['emojiId', 'emojiType', 'message_id'], required: ['emojiId', 'emojiType', 'message_id'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -22,12 +22,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class FetchEmojiLike extends BaseAction<Payload, any> { export class FetchEmojiLike extends BaseAction<Payload, any> {
actionName = ActionName.FetchEmojiLike; actionName = ActionName.FetchEmojiLike;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.CoreContext.apis.MsgApi;
const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msgIdPeer) throw new Error('消息不存在'); if (!msgIdPeer) throw new Error('消息不存在');
const msg = (await NTQQMsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0]; const msg = (await NTQQMsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0];
return await NTQQMsgApi.getMsgEmojiLikesList(msgIdPeer.Peer, msg.msgSeq, payload.emojiId, payload.emojiType, payload.count); return await NTQQMsgApi.getMsgEmojiLikesList(msgIdPeer.Peer, msg.msgSeq, payload.emojiId, payload.emojiType, parseInt((payload.count || '0').toString()) || 20);
} }
} }

View File

@@ -5,8 +5,8 @@ import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
category: { type: 'number' }, category: { type: ['number', 'string'] },
count: { type: 'number' }, count: { type: ['number', 'string'] },
}, },
required: ['category', 'count'], required: ['category', 'count'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -16,9 +16,8 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetCollectionList extends BaseAction<Payload, any> { export class GetCollectionList extends BaseAction<Payload, any> {
actionName = ActionName.GetCollectionList; actionName = ActionName.GetCollectionList;
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQCollectionApi = this.CoreContext.apis.CollectionApi; const NTQQCollectionApi = this.CoreContext.apis.CollectionApi;
return await NTQQCollectionApi.getAllCollection(payload.category, payload.count); return await NTQQCollectionApi.getAllCollection(parseInt(payload.category.toString()), parseInt(payload.count.toString()));
} }
} }

View File

@@ -4,16 +4,10 @@ import { ActionName } from '../types';
export class GetFriendWithCategory extends BaseAction<void, any> { export class GetFriendWithCategory extends BaseAction<void, any> {
actionName = ActionName.GetFriendsWithCategory; actionName = ActionName.GetFriendsWithCategory;
async _handle(payload: void) { async _handle(payload: void) {
if (this.CoreContext.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
//全新逻辑
return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({ return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({
...category, ...category,
buddyList: OB11Constructor.friendsV2(category.buddyList), buddyList: OB11Constructor.friendsV2(category.buddyList),
})); }));
} else {
throw new Error('this ntqq version not support, must be 26702 or later');
}
} }
} }

View File

@@ -9,7 +9,7 @@ export class GetProfileLike extends BaseAction<void, any> {
const ret = await NTQQUserApi.getProfileLike(this.CoreContext.selfInfo.uid); const ret = await NTQQUserApi.getProfileLike(this.CoreContext.selfInfo.uid);
const listdata: any[] = ret.info.userLikeInfos[0].favoriteInfo.userInfos; const listdata: any[] = ret.info.userLikeInfos[0].favoriteInfo.userInfos;
for (let i = 0; i < listdata.length; i++) { for (let i = 0; i < listdata.length; i++) {
listdata[i].uin = parseInt((await NTQQUserApi.getUinByUid(listdata[i].uid)) || ''); listdata[i].uin = parseInt((await NTQQUserApi.getUinByUidV2(listdata[i].uid)) || '');
} }
return listdata; return listdata;
} }

View File

@@ -5,7 +5,6 @@ export class GetRobotUinRange extends BaseAction<void, Array<any>> {
actionName = ActionName.GetRobotUinRange; actionName = ActionName.GetRobotUinRange;
async _handle(payload: void) { async _handle(payload: void) {
// console.log(await NTQQUserApi.getRobotUinRange());
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.CoreContext.apis.UserApi;
return await NTQQUserApi.getRobotUinRange(); return await NTQQUserApi.getRobotUinRange();
} }

View File

@@ -3,7 +3,6 @@ import { ActionName } from '../types';
import { FromSchema, JSONSchema } from 'json-schema-to-ts'; import { FromSchema, JSONSchema } from 'json-schema-to-ts';
import { checkFileReceived, uri2local } from '@/common/utils/file'; import { checkFileReceived, uri2local } from '@/common/utils/file';
import fs from 'fs'; import fs from 'fs';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {

View File

@@ -6,9 +6,9 @@ import { FromSchema, JSONSchema } from 'json-schema-to-ts';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
status: { type: 'number' }, status: { type: ['number', 'string'] },
extStatus: { type: 'number' }, extStatus: { type: ['number', 'string'] },
batteryStatus: { type: 'number' }, batteryStatus: { type: ['number', 'string'] },
}, },
required: ['status', 'extStatus', 'batteryStatus'], required: ['status', 'extStatus', 'batteryStatus'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -20,14 +20,12 @@ export class SetOnlineStatus extends BaseAction<Payload, null> {
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
// 可设置状态
// { status: 10, extStatus: 1027, batteryStatus: 0 }
// { status: 30, extStatus: 0, batteryStatus: 0 }
// { status: 50, extStatus: 0, batteryStatus: 0 }
// { status: 60, extStatus: 0, batteryStatus: 0 }
// { status: 70, extStatus: 0, batteryStatus: 0 }
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.CoreContext.apis.UserApi;
const ret = await NTQQUserApi.setSelfOnlineStatus(payload.status, payload.extStatus, payload.batteryStatus); const ret = await NTQQUserApi.setSelfOnlineStatus(
parseInt(payload.status.toString()),
parseInt(payload.extStatus.toString()),
parseInt(payload.batteryStatus.toString())
);
if (ret.result !== 0) { if (ret.result !== 0) {
throw new Error('设置在线状态失败'); throw new Error('设置在线状态失败');
} }

View File

@@ -7,7 +7,7 @@ const SchemaData = {
properties: { properties: {
nick: { type: 'string' }, nick: { type: 'string' },
longNick: { type: 'string' }, longNick: { type: 'string' },
sex: { type: 'number' },//传Sex值建议传0 sex: { type: ['number', 'string'] },//传Sex值建议传0
}, },
required: ['nick', 'longNick', 'sex'], required: ['nick', 'longNick', 'sex'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -23,7 +23,7 @@ export class SetSelfProfile extends BaseAction<Payload, any | null> {
const ret = await NTQQUserApi.modifySelfProfile({ const ret = await NTQQUserApi.modifySelfProfile({
nick: payload.nick, nick: payload.nick,
longNick: payload.longNick, longNick: payload.longNick,
sex: payload.sex, sex: parseInt(payload.sex.toString()),
birthday: { birthday_year: '', birthday_month: '', birthday_day: '' }, birthday: { birthday_year: '', birthday_month: '', birthday_day: '' },
location: undefined, location: undefined,
}); });

View File

@@ -28,19 +28,6 @@ const GetFileBase_PayloadSchema = {
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> { export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
PayloadSchema: any = GetFileBase_PayloadSchema; PayloadSchema: any = GetFileBase_PayloadSchema;
private getElement(msg: RawMessage): { id: string, element: VideoElement | FileElement } {
let element = msg.elements.find(e => e.fileElement);
if (!element) {
element = msg.elements.find(e => e.videoElement);
if (element) {
return { id: element.elementId, element: element.videoElement };
} else {
throw new Error('找不到文件');
}
}
return { id: element.elementId, element: element.fileElement };
}
async _handle(payload: GetFilePayload): Promise<GetFileResponse> { async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.CoreContext.apis.FriendApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.CoreContext.apis.UserApi;
@@ -92,7 +79,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
file_size: fileSize, file_size: fileSize,
file_name: fileName, file_name: fileName,
}; };
if (true/*enableLocalFile2Url*/) { if (true/*enableLocalFile2Url*/ && downloadPath) {
try { try {
res.base64 = await fs.readFile(downloadPath, 'base64'); res.base64 = await fs.readFile(downloadPath, 'base64');
} catch (e) { } catch (e) {
@@ -132,7 +119,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
file_size: NTSearchNameResult[0].fileSize.toString(), file_size: NTSearchNameResult[0].fileSize.toString(),
file_name: NTSearchNameResult[0].fileName, file_name: NTSearchNameResult[0].fileName,
}; };
if (true/*enableLocalFile2Url*/) { if (true/*enableLocalFile2Url*/ && downloadPath) {
try { try {
res.base64 = await fs.readFile(downloadPath, 'base64'); res.base64 = await fs.readFile(downloadPath, 'base64');
} catch (e) { } catch (e) {

View File

@@ -13,7 +13,7 @@ interface FileResponse {
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
thread_count: { type: 'number' }, thread_count: { type: ['number', 'string'] },
url: { type: 'string' }, url: { type: 'string' },
base64: { type: 'string' }, base64: { type: 'string' },
name: { type: 'string' }, name: { type: 'string' },

View File

@@ -39,15 +39,16 @@ export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
throw Error('找不到相关的聊天记录' + data?.errMsg); throw Error('找不到相关的聊天记录' + data?.errMsg);
} }
const msgList = data.msgList; 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'); const resMsg = await OB11Constructor.message(this.CoreContext, this.OneBotContext, msg);
if (!resMsg) return;
resMsg.message_id = MessageUnique.createMsg({ resMsg.message_id = MessageUnique.createMsg({
guildId: '', guildId: '',
chatType: msg.chatType, chatType: msg.chatType,
peerUid: msg.peerUid, peerUid: msg.peerUid,
}, msg.msgId)!; }, msg.msgId)!;
return resMsg; return resMsg;
})); }))).filter(msg => !!msg);
messages.map(msg => { messages.map(msg => {
(<OB11ForwardMessage>msg).content = msg.message; (<OB11ForwardMessage>msg).content = msg.message;
delete (<any>msg).message; delete (<any>msg).message;

View File

@@ -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); 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, this.OneBotContext, msg)))).filter(msg => !!msg);
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };
} }
} }

View File

@@ -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, this.OneBotContext, msg)))).filter(msg => !!msg);
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };
} }
} }

View File

@@ -0,0 +1,10 @@
import BaseAction from '../BaseAction';
import { ActionName } from '../types';
export default class SetModelShow extends BaseAction<null, null> {
actionName = ActionName.SetModelShow;
async _handle(payload: null): Promise<null> {
return null;
}
}

View File

@@ -20,9 +20,7 @@ export default class DelEssenceMsg extends BaseAction<Payload, any> {
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) throw new Error('msg not found');
throw new Error('msg not found');
}
return await NTQQGroupApi.removeGroupEssence( return await NTQQGroupApi.removeGroupEssence(
msg.Peer.peerUid, msg.Peer.peerUid,
msg.MsgId, msg.MsgId,

View File

@@ -9,7 +9,7 @@ const SchemaData = {
group_id: { type: ['number', 'string'] }, group_id: { type: ['number', 'string'] },
pages: { type: 'number' }, pages: { type: 'number' },
}, },
required: ['group_id', 'pages'], required: ['group_id'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
type Payload = FromSchema<typeof SchemaData>; type Payload = FromSchema<typeof SchemaData>;
@@ -20,7 +20,7 @@ export class GetGroupEssence extends BaseAction<Payload, GroupEssenceMsgRet> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.CoreContext.apis.WebApi;
const ret = await NTQQWebApi.getGroupEssenceMsg(payload.group_id.toString(), payload.pages.toString()); const ret = await NTQQWebApi.getGroupEssenceMsg(payload.group_id.toString(), (payload.pages || "0").toString());
if (!ret) { if (!ret) {
throw new Error('获取失败'); throw new Error('获取失败');
} }

View File

@@ -21,11 +21,8 @@ class GetGroupInfo extends BaseAction<Payload, OB11Group> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const group = (await NTQQGroupApi.getGroups()).find(e => e.groupCode == payload.group_id.toString()); const group = (await NTQQGroupApi.getGroups()).find(e => e.groupCode == payload.group_id.toString());
if (group) { if (!group) throw `${payload.group_id}不存在`;
return OB11Constructor.group(group); return OB11Constructor.group(group);
} else {
throw `${payload.group_id}不存在`;
}
} }
} }

View File

@@ -20,7 +20,7 @@ class GetGroupList extends BaseAction<Payload, OB11Group[]> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const groupList: Group[] = await NTQQGroupApi.getGroups(payload?.no_cache === true || payload.no_cache === 'true'); const groupList: Group[] = await NTQQGroupApi.getGroups(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache);
return OB11Constructor.groups(groupList); return OB11Constructor.groups(groupList);
} }
} }

View File

@@ -24,15 +24,11 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.CoreContext.apis.UserApi;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.CoreContext.apis.WebApi;
const isNocache = payload.no_cache == true || payload.no_cache === 'true'; const isNocache = typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache;
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) { if (!uid) throw (`Uin2Uid Error ${payload.user_id}不存在`);
throw (`Uin2Uid Error ${payload.user_id}不存在`);
}
const member = await NTQQGroupApi.getGroupMemberV2(payload.group_id.toString(), uid, isNocache); const member = await NTQQGroupApi.getGroupMemberV2(payload.group_id.toString(), uid, isNocache);
if (!member) { if (!member) throw (`群(${payload.group_id})成员${payload.user_id}不存在`);
throw (`群(${payload.group_id})成员${payload.user_id}不存在`);
}
try { try {
const info = (await NTQQUserApi.getUserDetailInfo(member.uid)); const info = (await NTQQUserApi.getUserDetailInfo(member.uid));
this.CoreContext.context.logger.logDebug('群成员详细信息结果', info); this.CoreContext.context.logger.logDebug('群成员详细信息结果', info);
@@ -42,7 +38,6 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
} }
const date = Math.round(Date.now() / 1000); const date = Math.round(Date.now() / 1000);
const retMember = OB11Constructor.groupMember(payload.group_id.toString(), member); const retMember = OB11Constructor.groupMember(payload.group_id.toString(), member);
if (!this.CoreContext.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
const SelfInfoInGroup = await NTQQGroupApi.getGroupMemberV2(payload.group_id.toString(), this.CoreContext.selfInfo.uid, isNocache); const SelfInfoInGroup = await NTQQGroupApi.getGroupMemberV2(payload.group_id.toString(), this.CoreContext.selfInfo.uid, isNocache);
let isPrivilege = false; let isPrivilege = false;
if (SelfInfoInGroup) { if (SelfInfoInGroup) {
@@ -58,21 +53,9 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
retMember.level = webGroupMembers[i]?.lv.level.toString(); retMember.level = webGroupMembers[i]?.lv.level.toString();
} }
} }
} else {
const LastestMsgList = await NTQQGroupApi.getLatestMsg(payload.group_id.toString(), [payload.user_id.toString()]);
if (LastestMsgList?.msgList?.length && LastestMsgList?.msgList?.length > 0) {
const last_send_time = LastestMsgList.msgList[0].msgTime;
if (last_send_time && last_send_time != '0' && last_send_time != '') {
retMember.last_sent_time = parseInt(last_send_time);
retMember.join_time = Math.round(Date.now() / 1000);//兜底数据 防止群管乱杀
}
}
}
} else {
// Mlikiowa V2.0.2 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());
} }
retMember.last_sent_time = parseInt((await this.CoreContext.apis.GroupApi.getGroupMember(payload.group_id.toString(), retMember.user_id))?.lastSpeakTime || date.toString());
retMember.join_time = parseInt((await this.CoreContext.apis.GroupApi.getGroupMember(payload.group_id.toString(), retMember.user_id))?.joinTime || date.toString());
return retMember; return retMember;
} }
} }

View File

@@ -22,23 +22,16 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.CoreContext.apis.WebApi;
const isNocache = payload.no_cache == true || payload.no_cache === 'true';
// const GroupList = await NTQQGroupApi.getGroups(isNocache);
// const group = GroupList.find(item => item.groupCode == payload.group_id);
// if (!group) {
// throw (`群${payload.group_id}不存在`);
// }
const groupMembers = await NTQQGroupApi.getGroupMembers(payload.group_id.toString()); const groupMembers = await NTQQGroupApi.getGroupMembers(payload.group_id.toString());
const groupMembersArr = Array.from(groupMembers.values()); const groupMembersArr = Array.from(groupMembers.values());
const groupMembersUids = groupMembersArr.map(e => e.uid);
let _groupMembers = groupMembersArr.map(item => { let _groupMembers = groupMembersArr.map(item => {
return OB11Constructor.groupMember(payload.group_id.toString(), item); return OB11Constructor.groupMember(payload.group_id.toString(), item);
}); });
const MemberMap: Map<number, OB11GroupMember> = new Map<number, OB11GroupMember>(); const MemberMap: Map<number, OB11GroupMember> = new Map<number, OB11GroupMember>();
// 转为Map 方便索引
const GroupMemberUids: string[] = [];
const date = Math.round(Date.now() / 1000); const date = Math.round(Date.now() / 1000);
for (let i = 0, len = _groupMembers.length; i < len; i++) { for (let i = 0, len = _groupMembers.length; i < len; i++) {
// 保证基础数据有这个 同时避免群管插件过于依赖这个杀了 // 保证基础数据有这个 同时避免群管插件过于依赖这个杀了
_groupMembers[i].join_time = date; _groupMembers[i].join_time = date;
@@ -46,10 +39,14 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
MemberMap.set(_groupMembers[i].user_id, _groupMembers[i]); MemberMap.set(_groupMembers[i].user_id, _groupMembers[i]);
} }
if (!this.CoreContext.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
const selfRole = groupMembers.get(this.CoreContext.selfInfo.uid)?.role; const selfRole = groupMembers.get(this.CoreContext.selfInfo.uid)?.role;
const isPrivilege = selfRole === 3 || selfRole === 4; const isPrivilege = selfRole === 3 || selfRole === 4;
_groupMembers.forEach(item => {
item.last_sent_time = date;
item.join_time = date;
});
if (isPrivilege) { if (isPrivilege) {
const webGroupMembers = await NTQQWebApi.getGroupMembers(payload.group_id.toString()); const webGroupMembers = await NTQQWebApi.getGroupMembers(payload.group_id.toString());
for (let i = 0, len = webGroupMembers.length; i < len; i++) { for (let i = 0, len = webGroupMembers.length; i < len; i++) {
@@ -65,39 +62,7 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
MemberMap.set(webGroupMembers[i]?.uin, MemberData); MemberMap.set(webGroupMembers[i]?.uin, MemberData);
} }
} }
} else {
if (isNocache) {
const DateMap = await NTQQGroupApi.getGroupMemberLatestSendTimeCache(payload.group_id.toString(), groupMembersUids);//开始从本地拉取
for (const DateUin of DateMap.keys()) {
const MemberData = MemberMap.get(parseInt(DateUin));
if (MemberData) {
MemberData.last_sent_time = parseInt(DateMap.get(DateUin)!);
//join_time 有基础数据兜底
} }
}
} else {
_groupMembers.forEach(item => {
item.last_sent_time = date;
item.join_time = date;
});
}
}
} else {
// Mlikiowa V2.0.2 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());
// });
}
// 还原索引到Array 一同返回
// let retData: any[] = [];
// for (let retMem of MemberMap.values()) {
// retMem.level = TypeConvert.toString(retMem.level) as any;
// retData.push(retMem)
// }
// _groupMembers = Array.from(retData);
_groupMembers = Array.from(MemberMap.values()); _groupMembers = Array.from(MemberMap.values());
return _groupMembers; return _groupMembers;

View File

@@ -24,22 +24,22 @@ export class GetGroupSystemMsg extends BaseAction<void, any> {
if (SSNotify.type == 1) { if (SSNotify.type == 1) {
retData.InvitedRequest.push({ retData.InvitedRequest.push({
request_id: SSNotify.seq, request_id: SSNotify.seq,
invitor_uin: await NTQQUserApi.getUinByUid(SSNotify.user1?.uid), invitor_uin: await NTQQUserApi.getUinByUidV2(SSNotify.user1?.uid),
invitor_nick: SSNotify.user1?.nickName, invitor_nick: SSNotify.user1?.nickName,
group_id: SSNotify.group?.groupCode, group_id: SSNotify.group?.groupCode,
group_name: SSNotify.group?.groupName, group_name: SSNotify.group?.groupName,
checked: SSNotify.status === 1 ? false : true, checked: SSNotify.status === 1 ? false : true,
actor: await NTQQUserApi.getUinByUid(SSNotify.user2?.uid) || 0, actor: await NTQQUserApi.getUinByUidV2(SSNotify.user2?.uid) || 0,
}); });
} else if (SSNotify.type == 7) { } else if (SSNotify.type == 7) {
retData.join_requests.push({ retData.join_requests.push({
request_id: SSNotify.seq, request_id: SSNotify.seq,
requester_uin: await NTQQUserApi.getUinByUid(SSNotify.user1?.uid), requester_uin: await NTQQUserApi.getUinByUidV2(SSNotify.user1?.uid),
requester_nick: SSNotify.user1?.nickName, requester_nick: SSNotify.user1?.nickName,
group_id: SSNotify.group?.groupCode, group_id: SSNotify.group?.groupCode,
group_name: SSNotify.group?.groupName, group_name: SSNotify.group?.groupName,
checked: SSNotify.status === 1 ? false : true, checked: SSNotify.status === 1 ? false : true,
actor: await NTQQUserApi.getUinByUid(SSNotify.user2?.uid) || 0, actor: await NTQQUserApi.getUinByUidV2(SSNotify.user2?.uid) || 0,
}); });
} }
} }

View File

@@ -8,7 +8,7 @@ const SchemaData = {
properties: { properties: {
group_id: { type: ['number', 'string'] }, group_id: { type: ['number', 'string'] },
user_id: { type: ['number', 'string'] }, user_id: { type: ['number', 'string'] },
enable: { type: 'boolean' }, enable: { type: ['boolean', 'string'] },
}, },
required: ['group_id', 'user_id'], required: ['group_id', 'user_id'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
@@ -20,11 +20,12 @@ export default class SetGroupAdmin extends BaseAction<Payload, null> {
PayloadSchema = SchemaData; PayloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const enable = typeof payload.enable === 'string' ? payload.enable === 'true' : !!payload.enable;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.CoreContext.apis.GroupApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.CoreContext.apis.UserApi;
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('get Uid Error'); if (!uid) throw new Error('get Uid Error');
await NTQQGroupApi.setMemberRole(payload.group_id.toString(), uid, payload.enable ? GroupMemberRole.admin : GroupMemberRole.normal); await NTQQGroupApi.setMemberRole(payload.group_id.toString(), uid, enable ? GroupMemberRole.admin : GroupMemberRole.normal);
return null; return null;
} }
} }

View File

@@ -6,7 +6,7 @@ const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
group_id: { type: ['number', 'string'] }, group_id: { type: ['number', 'string'] },
is_dismiss: { type: 'boolean' }, is_dismiss: { type: ['boolean', 'string'] },
}, },
required: ['group_id'], required: ['group_id'],
} as const satisfies JSONSchema; } as const satisfies JSONSchema;

View File

@@ -0,0 +1,10 @@
import BaseAction from '../BaseAction';
import { ActionName } from '../types';
export default class GetGuildProfile extends BaseAction<null, null> {
actionName = ActionName.GetGuildProfile;
async _handle(payload: null): Promise<null> {
return null;
}
}

View File

@@ -23,7 +23,7 @@ import GoCQHTTPGetStrangerInfo from './go-cqhttp/GetStrangerInfo';
import SendLike from './user/SendLike'; import SendLike from './user/SendLike';
import SetGroupAddRequest from './group/SetGroupAddRequest'; import SetGroupAddRequest from './group/SetGroupAddRequest';
import SetGroupLeave from './group/SetGroupLeave'; import SetGroupLeave from './group/SetGroupLeave';
import GetGuildList from './group/GetGuildList'; import GetGuildList from './guild/GetGuildList';
import SetFriendAddRequest from './user/SetFriendAddRequest'; import SetFriendAddRequest from './user/SetFriendAddRequest';
import SetGroupWholeBan from './group/SetGroupWholeBan'; import SetGroupWholeBan from './group/SetGroupWholeBan';
import SetGroupName from './group/SetGroupName'; import SetGroupName from './group/SetGroupName';
@@ -76,6 +76,8 @@ import { FetchEmojiLike } from './extends/FetchEmojiLike';
import { NapCatCore } from '@/core'; import { NapCatCore } from '@/core';
import { NapCatOneBot11Adapter } from '@/onebot'; import { NapCatOneBot11Adapter } from '@/onebot';
import GetGuildProfile from './guild/GetGuildProfile';
import SetModelShow from './go-cqhttp/SetModelShow';
export type ActionMap = Map<string, BaseAction<any, any>>; export type ActionMap = Map<string, BaseAction<any, any>>;
@@ -161,6 +163,8 @@ export function createActionMap(onebotContext: NapCatOneBot11Adapter, coreContex
new SetGroupHeader(onebotContext, coreContext), new SetGroupHeader(onebotContext, coreContext),
new FetchCustomFace(onebotContext, coreContext), new FetchCustomFace(onebotContext, coreContext),
new GoCQHTTPUploadPrivateFile(onebotContext, coreContext), new GoCQHTTPUploadPrivateFile(onebotContext, coreContext),
new GetGuildProfile(onebotContext, coreContext),
new SetModelShow(onebotContext, coreContext),
]; ];
const actionMap = new Map(); const actionMap = new Map();
for (const action of actionHandlers) { for (const action of actionHandlers) {

View File

@@ -7,7 +7,7 @@ import { MessageUnique } from '@/common/utils/MessageUnique';
const SchemaData = { const SchemaData = {
type: 'object', type: 'object',
properties: { properties: {
message_id: { type: 'number' }, message_id: { type: ['number', 'string'] },
group_id: { type: ['number', 'string'] }, group_id: { type: ['number', 'string'] },
user_id: { type: ['number', 'string'] }, user_id: { type: ['number', 'string'] },
}, },
@@ -31,7 +31,7 @@ class ForwardSingleMsg extends BaseAction<Payload, null> {
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.CoreContext.apis.MsgApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(payload.message_id); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error(`无法找到消息${payload.message_id}`); throw new Error(`无法找到消息${payload.message_id}`);
} }

View File

@@ -28,8 +28,8 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
if (!payload.message_id) { if (!payload.message_id) {
throw Error('参数message_id不能为空'); throw Error('参数message_id不能为空');
} }
const MsgShortId = await MessageUnique.getShortIdByMsgId(payload.message_id.toString()); const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
const msgIdWithPeer = await MessageUnique.getMsgIdAndPeerByShortId(MsgShortId || parseInt(payload.message_id.toString())); const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId || parseInt(payload.message_id.toString()));
if (!msgIdWithPeer) { if (!msgIdWithPeer) {
throw ('消息不存在'); throw ('消息不存在');
} }
@@ -37,7 +37,8 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
const msg = await NTQQMsgApi.getMsgsByMsgId( const msg = await NTQQMsgApi.getMsgsByMsgId(
peer, peer,
[msgIdWithPeer?.MsgId || payload.message_id.toString()]); [msgIdWithPeer?.MsgId || payload.message_id.toString()]);
const retMsg = await OB11Constructor.message(this.CoreContext, msg.msgList[0], 'array'); const retMsg = await OB11Constructor.message(this.CoreContext, this.OneBotContext, msg.msgList[0], 'array');
if (!retMsg) throw Error('消息为空');
try { try {
retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!; retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!;
retMsg.message_seq = retMsg.message_id; retMsg.message_seq = retMsg.message_id;

View File

@@ -56,8 +56,8 @@ const _handlers: {
if (atQQ === 'all') return SendMsgElementConstructor.at(coreContext, atQQ, atQQ, AtType.atAll, '全体成员'); if (atQQ === 'all') return SendMsgElementConstructor.at(coreContext, atQQ, atQQ, AtType.atAll, '全体成员');
// then the qq is a group member // then the qq is a group member
// Mlikiowa V2.0.2 Refactor Todo // Mlikiowa V2.0.21 Refactor Todo
const uid = await coreContext.apis.UserApi.getUidByUinV2(atQQ); const uid = await coreContext.apis.UserApi.getUidByUinV2(`${atQQ}`);
if (!uid) throw new Error('Get Uid Error'); if (!uid) throw new Error('Get Uid Error');
return SendMsgElementConstructor.at(coreContext, atQQ, uid, AtType.atUser, ''); return SendMsgElementConstructor.at(coreContext, atQQ, uid, AtType.atUser, '');
}, },
@@ -161,7 +161,7 @@ const _handlers: {
} else { } else {
postData = data; postData = data;
} }
// Mlikiowa V2.0.2 Refactor Todo // Mlikiowa V2.0.21 Refactor Todo
const signUrl = obContext.configLoader.configData.musicSignUrl; const signUrl = obContext.configLoader.configData.musicSignUrl;
if (!signUrl) { if (!signUrl) {
if (data.type === 'qq') { if (data.type === 'qq') {

View File

@@ -105,6 +105,7 @@ async function createContext(coreContext: NapCatCore, payload: OB11PostSendMsg,
return { return {
chatType: isBuddy ? ChatType.friend : ChatType.temp, chatType: isBuddy ? ChatType.friend : ChatType.temp,
peerUid: Uid!, peerUid: Uid!,
guildId: payload.group_id?.toString() || '',
}; };
} }
throw '请指定 group_id 或 user_id'; throw '请指定 group_id 或 user_id';
@@ -152,7 +153,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
const messages = normalize( const messages = normalize(
payload.message, payload.message,
payload.auto_escape === true || payload.auto_escape === 'true', typeof payload.auto_escape === 'string' ? payload.auto_escape === 'true' : !!payload.auto_escape
); );
if (getSpecialMsgNum(payload, OB11MessageDataType.node)) { if (getSpecialMsgNum(payload, OB11MessageDataType.node)) {

View File

@@ -104,5 +104,7 @@ export enum ActionName {
FetchCustomFace = 'fetch_custom_face', FetchCustomFace = 'fetch_custom_face',
GOCQHTTP_UploadPrivateFile = 'upload_private_file', GOCQHTTP_UploadPrivateFile = 'upload_private_file',
TestApi01 = 'test_api_01', TestApi01 = 'test_api_01',
FetchEmojiLike = 'fetch_emoji_like' FetchEmojiLike = 'fetch_emoji_like',
GetGuildProfile = "get_guild_service_profile",
SetModelShow = "_set_model_show"
} }

View File

@@ -67,7 +67,7 @@ export class GetCookies extends BaseAction<Payload, Response> {
const cookiesObject = await NTQQUserApi.getCookies(payload.domain); const cookiesObject = await NTQQUserApi.getCookies(payload.domain);
//把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起 //把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; '); const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ');
const bkn = NTQQWebApi.getBknFromCookie(cookiesObject.p_skey); const bkn = cookiesObject?.skey ? NTQQWebApi.getBknFromCookie(cookiesObject) : '';
return { cookies, bkn }; return { cookies, bkn };
} }
} }

View File

@@ -20,6 +20,6 @@ export default class GetFriendList extends BaseAction<Payload, OB11User[]> {
async _handle(payload: Payload) { async _handle(payload: Payload) {
//全新逻辑 //全新逻辑
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.CoreContext.apis.FriendApi;
return OB11Constructor.friendsV2(await NTQQFriendApi.getBuddyV2(payload?.no_cache === true || payload?.no_cache === 'true')); return OB11Constructor.friendsV2(await NTQQFriendApi.getBuddyV2(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache));
} }
} }

View File

@@ -24,7 +24,7 @@ export default class GetRecentContact extends BaseAction<Payload, any> {
const FastMsg = await NTQQMsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]); const FastMsg = await NTQQMsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]);
if (FastMsg.msgList.length > 0) { if (FastMsg.msgList.length > 0) {
//扩展ret.info.changedList //扩展ret.info.changedList
const lastestMsg = await OB11Constructor.message(this.CoreContext, FastMsg.msgList[0], 'array'); const lastestMsg = await OB11Constructor.message(this.CoreContext, this.OneBotContext,FastMsg.msgList[0], 'array');
return { return {
lastestMsg: lastestMsg, lastestMsg: lastestMsg,
peerUin: t.peerUin, peerUin: t.peerUin,

View File

@@ -6,14 +6,14 @@ export class OB11InputStatusEvent extends OB11BaseNoticeEvent {
notice_type = 'notify'; notice_type = 'notify';
sub_type = 'input_status'; sub_type = 'input_status';
status_text = '对方正在输入...'; status_text = '对方正在输入...';
eventType = 1; event_type = 1;
user_id = 0; user_id = 0;
group_id = 0; group_id = 0;
constructor(core: NapCatCore, user_id: number, eventType: number, status_text: string) { constructor(core: NapCatCore, user_id: number, eventType: number, status_text: string) {
super(core); super(core);
this.user_id = user_id; this.user_id = user_id;
this.eventType = eventType; this.event_type = eventType;
this.status_text = status_text; this.status_text = status_text;
} }
} }

View File

@@ -42,10 +42,18 @@ import { OB11BaseNoticeEvent } from '../event/notice/OB11BaseNoticeEvent';
import { OB11GroupEssenceEvent } from '../event/notice/OB11GroupEssenceEvent'; import { OB11GroupEssenceEvent } from '../event/notice/OB11GroupEssenceEvent';
import { MessageUnique } from '@/common/utils/MessageUnique'; import { MessageUnique } from '@/common/utils/MessageUnique';
import { NapCatCore } from '@/core'; import { NapCatCore } from '@/core';
import { NapCatOneBot11Adapter } from '..';
export class OB11Constructor { export class OB11Constructor {
static async message(core: NapCatCore, msg: RawMessage, messagePostFormat: any): Promise<OB11Message> { static async message(
core: NapCatCore,
obcore: NapCatOneBot11Adapter,
msg: RawMessage,
messagePostFormat: string = obcore.configLoader.configData.messagePostFormat
): Promise<OB11Message | undefined> {
if (msg.senderUin == "0" || msg.senderUin == "") return;
if (msg.peerUin == "0" || msg.peerUin == "") return;
//跳过空消息
const NTQQGroupApi = core.apis.GroupApi; const NTQQGroupApi = core.apis.GroupApi;
const NTQQUserApi = core.apis.UserApi; const NTQQUserApi = core.apis.UserApi;
const NTQQFileApi = core.apis.FileApi; const NTQQFileApi = core.apis.FileApi;
@@ -75,8 +83,8 @@ export class OB11Constructor {
resMsg.sub_type = 'normal'; // 这里go-cqhttp是group而onebot11标准是normal, 蛋疼 resMsg.sub_type = 'normal'; // 这里go-cqhttp是group而onebot11标准是normal, 蛋疼
resMsg.group_id = parseInt(msg.peerUin); resMsg.group_id = parseInt(msg.peerUin);
//直接去QQNative取 //直接去QQNative取
const memberList = await NTQQGroupApi.getGroupMembers(msg.peerUin); let member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
const member = memberList.get(msg.senderUin!); if (!member) member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
if (member) { if (member) {
resMsg.sender.role = OB11Constructor.groupMemberRole(member.role); resMsg.sender.role = OB11Constructor.groupMemberRole(member.role);
resMsg.sender.nickname = member.nick; resMsg.sender.nickname = member.nick;
@@ -111,7 +119,7 @@ export class OB11Constructor {
const { atNtUid, content } = element.textElement; const { atNtUid, content } = element.textElement;
let atQQ = element.textElement.atUid; let atQQ = element.textElement.atUid;
if (!atQQ || atQQ === '0') { if (!atQQ || atQQ === '0') {
atQQ = await NTQQUserApi.getUinByUid(atNtUid); atQQ = await NTQQUserApi.getUinByUidV2(atNtUid);
} }
if (atQQ) { if (atQQ) {
qq = atQQ as `${number}`; qq = atQQ as `${number}`;
@@ -141,7 +149,7 @@ export class OB11Constructor {
message_data['type'] = OB11MessageDataType.reply; message_data['type'] = OB11MessageDataType.reply;
//log("收到回复消息", element.replyElement); //log("收到回复消息", element.replyElement);
try { 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 = { const peer = {
chatType: msg.chatType, chatType: msg.chatType,
peerUid: msg.peerUid, peerUid: msg.peerUid,
@@ -342,7 +350,8 @@ export class OB11Constructor {
MultiMsg.parentMsgPeer = ParentMsgPeer; MultiMsg.parentMsgPeer = ParentMsgPeer;
MultiMsg.parentMsgIdList = msg.parentMsgIdList; MultiMsg.parentMsgIdList = msg.parentMsgIdList;
MultiMsg.id = MessageUnique.createMsg(ParentMsgPeer, MultiMsg.msgId);//该ID仅用查看 无法调用 MultiMsg.id = MessageUnique.createMsg(ParentMsgPeer, MultiMsg.msgId);//该ID仅用查看 无法调用
const msgList = await OB11Constructor.message(core, MultiMsg, 'array'); const msgList = await OB11Constructor.message(core, obcore, MultiMsg, messagePostFormat);
if (!msgList) continue;
message_data['data']['content'].push(msgList); message_data['data']['content'].push(msgList);
//console.log("合并消息", msgList); //console.log("合并消息", msgList);
} }
@@ -408,7 +417,7 @@ export class OB11Constructor {
return; return;
} }
//log("group msg", msg); //log("group msg", msg);
// Mlikiowa V2.0.2 Refactor Todo // Mlikiowa V2.0.21 Refactor Todo
// if (msg.senderUin && msg.senderUin !== '0') { // if (msg.senderUin && msg.senderUin !== '0') {
// const member = await getGroupMember(msg.peerUid, msg.senderUin); // const member = await getGroupMember(msg.peerUid, msg.senderUin);
// if (member && member.cardName !== msg.sendMemberName) { // if (member && member.cardName !== msg.sendMemberName) {

View File

@@ -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);
}

View File

@@ -25,7 +25,6 @@ import { WebUiDataRuntime } from '@/webui/src/helper/Data';
import { OB11InputStatusEvent } from '@/onebot/event/notice/OB11InputStatusEvent'; import { OB11InputStatusEvent } from '@/onebot/event/notice/OB11InputStatusEvent';
import { MessageUnique } from '@/common/utils/MessageUnique'; import { MessageUnique } from '@/common/utils/MessageUnique';
import { OB11Constructor } from '@/onebot/helper/data'; import { OB11Constructor } from '@/onebot/helper/data';
import { logOB11Message } from '@/onebot/helper/log';
import { proxiedListenerOf } from '@/common/utils/proxy-handler'; import { proxiedListenerOf } from '@/common/utils/proxy-handler';
import { OB11FriendRequestEvent } from '@/onebot/event/request/OB11FriendRequest'; import { OB11FriendRequestEvent } from '@/onebot/event/request/OB11FriendRequest';
import { OB11GroupAdminNoticeEvent } from '@/onebot/event/notice/OB11GroupAdminNoticeEvent'; import { OB11GroupAdminNoticeEvent } from '@/onebot/event/notice/OB11GroupAdminNoticeEvent';
@@ -251,13 +250,12 @@ export class NapCatOneBot11Adapter {
.catch(e => this.context.logger.logError('处理消息失败', e)); .catch(e => this.context.logger.logError('处理消息失败', e));
for (const msg of msgList.filter(e => e.senderUin == this.core.selfInfo.uin)) { for (const msg of msgList.filter(e => e.senderUin == this.core.selfInfo.uin)) {
// console.log(msg); if (msg.sendStatus == 2 && !msgIdSend.get(msg.msgId)) {
if (!!msgIdSend.get(msg.msgId)) continue;
msgIdSend.put(msg.msgId, true); msgIdSend.put(msg.msgId, true);
if (msg.sendStatus == 2) {
// 完成后再post // 完成后再post
OB11Constructor.message(this.core, msg, this.configLoader.configData.messagePostFormat) OB11Constructor.message(this.core, this, msg)
.then((ob11Msg) => { .then((ob11Msg) => {
if (!ob11Msg) return;
ob11Msg.target_id = parseInt(msg.peerUin); ob11Msg.target_id = parseInt(msg.peerUin);
if (this.configLoader.configData.reportSelfMessage) { if (this.configLoader.configData.reportSelfMessage) {
msg.id = MessageUnique.createMsg({ msg.id = MessageUnique.createMsg({
@@ -267,7 +265,7 @@ export class NapCatOneBot11Adapter {
}, msg.msgId); }, msg.msgId);
this.emitMsg(msg); this.emitMsg(msg);
} else { } else {
logOB11Message(this.core, ob11Msg); // logOB11Message(this.core, ob11Msg);
} }
}); });
} }
@@ -426,9 +424,10 @@ export class NapCatOneBot11Adapter {
private async emitMsg(message: RawMessage) { private async emitMsg(message: RawMessage) {
const { debug, reportSelfMessage, messagePostFormat } = this.configLoader.configData; 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) => { OB11Constructor.message(this.core, this, message, messagePostFormat).then((ob11Msg) => {
this.context.logger.logDebug('收到消息: ', ob11Msg); if (!ob11Msg) return;
this.context.logger.logDebug('转化为 OB11Message', ob11Msg);
if (debug) { if (debug) {
ob11Msg.raw = message; ob11Msg.raw = message;
} else { } else {
@@ -436,8 +435,8 @@ export class NapCatOneBot11Adapter {
return; return;
} }
} }
logOB11Message(this.core, ob11Msg) // logOB11Message(this.core, ob11Msg)
.catch(e => this.context.logger.logError('logMessage error: ', e)); // .catch(e => this.context.logger.logError('logMessage error: ', e));
const isSelfMsg = ob11Msg.user_id.toString() == this.core.selfInfo.uin; const isSelfMsg = ob11Msg.user_id.toString() == this.core.selfInfo.uin;
if (isSelfMsg && !reportSelfMessage) { if (isSelfMsg && !reportSelfMessage) {
return; return;
@@ -484,6 +483,7 @@ export class NapCatOneBot11Adapter {
let operatorId = message.senderUin; let operatorId = message.senderUin;
for (const element of message.elements) { for (const element of message.elements) {
const operatorUid = element.grayTipElement?.revokeElement.operatorUid; const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
if (!operatorUid) return;
const operator = await this.core.apis.GroupApi.getGroupMember(message.peerUin, operatorUid); const operator = await this.core.apis.GroupApi.getGroupMember(message.peerUin, operatorUid);
operatorId = operator?.uin || message.senderUin; operatorId = operator?.uin || message.senderUin;
} }

View File

@@ -44,14 +44,16 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
resJson = await res.json(); resJson = await res.json();
//logDebug('新消息事件HTTP上报返回快速操作: ', JSON.stringify(resJson)); //logDebug('新消息事件HTTP上报返回快速操作: ', JSON.stringify(resJson));
} catch (e) { } catch (e) {
this.logger.logDebug('新消息事件HTTP上报没有返回快速操作不需要处理'); this.logger.logDebug('[OneBot] [Http Client] 新消息事件HTTP上报没有返回快速操作不需要处理');
return; return;
} }
try { try {
handleQuickOperation(this.coreContext, this.obContext, event as QuickActionEvent, resJson).then().catch(this.logger.logError); handleQuickOperation(this.coreContext, this.obContext, event as QuickActionEvent, resJson).then().catch(this.logger.logError);
} catch (e: any) { } catch (e: any) {
this.logger.logError('新消息事件HTTP上报返回快速操作失败', e); this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报返回快速操作失败', e);
} }
}).catch((e) => {
this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报失败', e);
}); });
} }

View File

@@ -6,6 +6,7 @@ import { ActionName } from '@/onebot/action/types';
import { OB11Response } from '@/onebot/action/OB11Response'; import { OB11Response } from '@/onebot/action/OB11Response';
import { LogWrapper } from '@/common/utils/log'; import { LogWrapper } from '@/common/utils/log';
import { ActionMap } from '@/onebot/action'; import { ActionMap } from '@/onebot/action';
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter { export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
isClosed: boolean = false; isClosed: boolean = false;
@@ -25,7 +26,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
} }
onEvent<T extends OB11EmitEventContent>(event: T) { onEvent<T extends OB11EmitEventContent>(event: T) {
if (this.connection) { if (this.connection && this.connection.readyState === WebSocket.OPEN) {
this.connection.send(JSON.stringify(event)); this.connection.send(JSON.stringify(event));
} }
} }
@@ -69,6 +70,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
let isClosedByError = false; let isClosedByError = false;
this.connection = new WebSocket(this.url, { this.connection = new WebSocket(this.url, {
maxPayload: 1024 * 1024 * 1024,
headers: { headers: {
'X-Self-ID': this.coreContext.selfInfo.uin, 'X-Self-ID': this.coreContext.selfInfo.uin,
'Authorization': `Bearer ${this.token}`, 'Authorization': `Bearer ${this.token}`,
@@ -76,14 +78,22 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
'User-Agent': 'OneBot/11', '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.connection.on('message', (data) => {
this.handleMessage(data); this.handleMessage(data);
}); });
this.connection.once('close', () => { this.connection.once('close', () => {
if (!isClosedByError) { if (!isClosedByError) {
this.logger.logError(`反向WebSocket (${this.url}) 连接意外关闭`); this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接意外关闭`);
this.logger.logError(`${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`); this.logger.logError(`[OneBot] [WebSocket Client] ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
if (!this.isClosed) { if (!this.isClosed) {
this.connection = null; this.connection = null;
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis); setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
@@ -92,8 +102,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
}); });
this.connection.on('error', (err) => { this.connection.on('error', (err) => {
isClosedByError = true; isClosedByError = true;
this.logger.logError(`反向WebSocket (${this.url}) 连接错误`, err); this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接错误`, err);
this.logger.logError(`${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`); this.logger.logError(`[OneBot] [WebSocket Client] ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
if (!this.isClosed) { if (!this.isClosed) {
this.connection = null; this.connection = null;
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis); setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
@@ -101,7 +111,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) { private async handleMessage(message: any) {
let receiveData: { action: ActionName, params?: any, echo?: any } = { action: ActionName.Unknown, params: {} }; let receiveData: { action: ActionName, params?: any, echo?: any } = { action: ActionName.Unknown, params: {} };
let echo = undefined; let echo = undefined;
@@ -109,7 +125,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
try { try {
receiveData = JSON.parse(message.toString()); receiveData = JSON.parse(message.toString());
echo = receiveData.echo; echo = receiveData.echo;
this.logger.logDebug('收到正向Websocket消息', receiveData); this.logger.logDebug('[OneBot] [WebSocket Client] 收到正向Websocket消息', receiveData);
} catch (e) { } catch (e) {
this.checkStateAndReply<any>(OB11Response.error('json解析失败,请检查数据格式', 1400, echo)); this.checkStateAndReply<any>(OB11Response.error('json解析失败,请检查数据格式', 1400, echo));
} }
@@ -119,6 +135,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
const packet = Object.assign({}, retdata); const packet = Object.assign({}, retdata);
this.checkStateAndReply<any>(packet); this.checkStateAndReply<any>(packet);
} catch (e) { } catch (e) {
this.logger.logError('[OneBot] [WebSocket Client] 发生错误', e);
this.checkStateAndReply<any>(OB11Response.error('不支持的api ' + receiveData.action, 1404, echo)); this.checkStateAndReply<any>(OB11Response.error('不支持的api ' + receiveData.action, 1404, echo));
} }
} }

View File

@@ -43,13 +43,34 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
this.server?.close(); this.server?.close();
this.app = undefined; this.app = undefined;
} }
cors(): any {
return (req: Request, res: Response, next: any) => {
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}
next();
};
}
private initializeServer() { private initializeServer() {
this.app = express(); this.app = express();
this.server = http.createServer(this.app); this.server = http.createServer(this.app);
this.app.use(express.json()); this.app.use(this.cors());
this.app.use(express.urlencoded({ extended: false })); this.app.use(express.urlencoded({ extended: true, limit: '5000mb' }));
this.app.use((req, res, next) => {
// 兼容处理没有带content-type的请求
req.headers['content-type'] = 'application/json';
const originalJson = express.json({ limit: '5000mb' });
originalJson(req, res, (err) => {
if (err) {
return res.status(400).send('Invalid JSON');
}
next();
});
});
this.app.use((req, res, next) => this.authorize(this.token, req, res, next)); this.app.use((req, res, next) => this.authorize(this.token, req, res, next));
this.app.use((req, res) => this.handleRequest(req, res)); this.app.use((req, res) => this.handleRequest(req, res));

View File

@@ -11,6 +11,7 @@ import { LogWrapper } from '@/common/utils/log';
import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent'; import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent';
import { IncomingMessage } from 'http'; import { IncomingMessage } from 'http';
import { ActionMap } from '@/onebot/action'; import { ActionMap } from '@/onebot/action';
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter { export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
wsServer: WebSocketServer; wsServer: WebSocketServer;
@@ -35,7 +36,8 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
this.logger = coreContext.context.logger; this.logger = coreContext.context.logger;
this.heartbeatInterval = heartbeatInterval; this.heartbeatInterval = heartbeatInterval;
this.wsServer = new WebSocketServer({ port: port, host: ip }); this.wsServer = new WebSocketServer({ port: port, host: ip, maxPayload: 1024 * 1024 * 1024, });
const core = coreContext;
this.wsServer.on('connection', async (wsClient, wsReq) => { this.wsServer.on('connection', async (wsClient, wsReq) => {
if (!this.isOpen) { if (!this.isOpen) {
wsClient.close(); wsClient.close();
@@ -43,9 +45,8 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
} }
//鉴权 //鉴权
this.authorize(token, wsClient, wsReq); 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('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Client Error:', err.message));
wsClient.on('message', (message) => { wsClient.on('message', (message) => {
this.handleMessage(wsClient, message).then().catch(this.logger.logError); this.handleMessage(wsClient, message).then().catch(this.logger.logError);
}); });
@@ -63,6 +64,14 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
}).on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Server Error:', err.message)); }).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) { onEvent<T extends OB11EmitEventContent>(event: T) {
this.wsClientsMutex.runExclusive(async () => { this.wsClientsMutex.runExclusive(async () => {
this.wsClients.forEach((wsClient) => { this.wsClients.forEach((wsClient) => {

View File

@@ -168,20 +168,25 @@ export async function NCoreInitShell() {
}); });
}); });
if (quickLoginUin && historyLoginList.some(u => u.uin === quickLoginUin)) { if (quickLoginUin) {
if (historyLoginList.some(u => u.uin === quickLoginUin)) {
logger.log('正在快速登录 ', quickLoginUin); logger.log('正在快速登录 ', quickLoginUin);
setTimeout(() => { setTimeout(() => {
loginService.quickLoginWithUin(quickLoginUin) loginService.quickLoginWithUin(quickLoginUin)
.then(result => { .then(result => {
if (result.loginErrorInfo.errMsg) { if (result.loginErrorInfo.errMsg) {
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg); logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
reject(); loginService.getQRCodePicture();
} }
}) })
.catch(e => reject(e)); .catch();
}, 1000); }, 1000);
} else { } else {
logger.log('没有 -q 指令指定快速登录,或未曾登录过这个 QQ,将使用二维码登录方式'); logger.logError('快速登录失败,未找到该 QQ 历史登录记录,将使用二维码登录方式');
loginService.getQRCodePicture();
}
} else {
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
if (historyLoginList.length > 0) { if (historyLoginList.length > 0) {
logger.log(`可用于快速登录的 QQ\n${ logger.log(`可用于快速登录的 QQ\n${
historyLoginList historyLoginList

View File

@@ -19,7 +19,7 @@ export let webUiPathWrapper: NapCatPathWrapper;
export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) { export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) {
webUiPathWrapper = pathWrapper; webUiPathWrapper = pathWrapper;
WebUiConfig = new WebUiConfigWrapper(); WebUiConfig = new WebUiConfigWrapper();
let log = logger.log.bind(logger); const log = logger.log.bind(logger);
const config = await WebUiConfig.GetWebUIConfig(); const config = await WebUiConfig.GetWebUIConfig();
if (config.port == 0) { if (config.port == 0) {
log('[NapCat] [WebUi] Current WebUi is not run.'); log('[NapCat] [WebUi] Current WebUi is not run.');

View File

@@ -30,7 +30,7 @@ async function onSettingWindowCreated(view: Element) {
SettingItem( SettingItem(
'<span id="napcat-update-title">Napcat</span>', '<span id="napcat-update-title">Napcat</span>',
undefined, undefined,
SettingButton('V2.0.2', 'napcat-update-button', 'secondary'), SettingButton('V2.0.21', 'napcat-update-button', 'secondary'),
), ),
]), ]),
SettingList([ SettingList([
@@ -176,6 +176,16 @@ async function onSettingWindowCreated(view: Element) {
), ),
SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs')) SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs'))
]), ]),
SettingItem(
'Telegram 群',
'https://t.me/+nLZEnpne-pQ1OWFl',
SettingButton('进去逛逛', 'open-telegram')
),
SettingItem(
'QQ 群',
'518662028',
SettingButton('我要进去', 'open-qq-group')
),
'</div>', '</div>',
].join(''), ].join(''),
'text/html', 'text/html',
@@ -188,6 +198,12 @@ async function onSettingWindowCreated(view: Element) {
doc.querySelector('#open-docs')?.addEventListener('click', () => { doc.querySelector('#open-docs')?.addEventListener('click', () => {
window.open('https://napneko.github.io/', '_blank'); 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 = ( const buildHostListItem = (
type: string, type: string,

View File

@@ -164,7 +164,7 @@ async function onSettingWindowCreated(view) {
SettingItem( SettingItem(
'<span id="napcat-update-title">Napcat</span>', '<span id="napcat-update-title">Napcat</span>',
void 0, void 0,
SettingButton("V2.0.2", "napcat-update-button", "secondary") SettingButton("V2.0.21", "napcat-update-button", "secondary")
) )
]), ]),
SettingList([ SettingList([
@@ -308,6 +308,16 @@ async function onSettingWindowCreated(view) {
), ),
SettingItem("NapCat 文档", "", SettingButton("看看文档", "open-docs")) SettingItem("NapCat 文档", "", SettingButton("看看文档", "open-docs"))
]), ]),
SettingItem(
"Telegram 群",
"https://t.me/+nLZEnpne-pQ1OWFl",
SettingButton("进去逛逛", "open-telegram")
),
SettingItem(
"QQ 群",
"518662028",
SettingButton("我要进去", "open-qq-group")
),
"</div>" "</div>"
].join(""), ].join(""),
"text/html" "text/html"
@@ -318,6 +328,12 @@ async function onSettingWindowCreated(view) {
doc.querySelector("#open-docs")?.addEventListener("click", () => { doc.querySelector("#open-docs")?.addEventListener("click", () => {
window.open("https://napneko.github.io/", "_blank"); 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 buildHostListItem = (type, host, index, inputAttrs = {}) => {
const dom = { const dom = {
container: document.createElement("setting-item"), container: document.createElement("setting-item"),