mirror of
https://github.com/NapNeko/NapCatQQ.git
synced 2025-07-19 12:03:37 +00:00
Compare commits
70 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
a8a2ffc33e | ||
![]() |
27c4543471 | ||
![]() |
50a02cb59e | ||
![]() |
50579bb9e6 | ||
![]() |
50512ca63c | ||
![]() |
8b3577b216 | ||
![]() |
7553aab932 | ||
![]() |
5dacdcfe5e | ||
![]() |
8645a412b7 | ||
![]() |
acad07a588 | ||
![]() |
51bbb480bb | ||
![]() |
f0306cd10a | ||
![]() |
25253ad9e7 | ||
![]() |
51f2fb8e8b | ||
![]() |
9e8d650cbd | ||
![]() |
d222ccfa58 | ||
![]() |
9a05aaa906 | ||
![]() |
00fdce8876 | ||
![]() |
29b51adf7d | ||
![]() |
8e14b39969 | ||
![]() |
d9fb4d6c4d | ||
![]() |
fcf2f4c5f2 | ||
![]() |
4e97501690 | ||
![]() |
b0402391fb | ||
![]() |
f05a862cf9 | ||
![]() |
3ea92d57c2 | ||
![]() |
254b85fbd8 | ||
![]() |
16371c0cc4 | ||
![]() |
2256d67e2b | ||
![]() |
0af0bdede6 | ||
![]() |
379f31b9de | ||
![]() |
771a524734 | ||
![]() |
560e18a610 | ||
![]() |
147bdfab95 | ||
![]() |
36b1b0f663 | ||
![]() |
91511e4c3f | ||
![]() |
6a72056b25 | ||
![]() |
62e0c57a50 | ||
![]() |
9d92270931 | ||
![]() |
f61321d5a6 | ||
![]() |
08ab2f8649 | ||
![]() |
82962c4b42 | ||
![]() |
bd24e8a4ad | ||
![]() |
6224d9a292 | ||
![]() |
bbc58f3671 | ||
![]() |
fcd620283f | ||
![]() |
a78def3d2d | ||
![]() |
43e94a5db0 | ||
![]() |
e77bcc1267 | ||
![]() |
9b458958b8 | ||
![]() |
35419ade29 | ||
![]() |
15bd2ee887 | ||
![]() |
9394bafa8e | ||
![]() |
94150a0c48 | ||
![]() |
8955fdfc23 | ||
![]() |
c13aa6a545 | ||
![]() |
c73b50bd4a | ||
![]() |
0a17a38bf1 | ||
![]() |
0f7bfe1d66 | ||
![]() |
cf3f488663 | ||
![]() |
5f536fdb73 | ||
![]() |
99d0b13cce | ||
![]() |
b04937f012 | ||
![]() |
91c9b059cf | ||
![]() |
35cc643440 | ||
![]() |
b23bb8c46a | ||
![]() |
64fdf62c4b | ||
![]() |
1c8a808571 | ||
![]() |
d8f0295032 | ||
![]() |
45df093fac |
@@ -19,16 +19,17 @@ NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现。
|
||||
**首次使用**请务必前往[官方文档](https://napneko.github.io/)查看使用教程。
|
||||
|
||||
## 相关链接
|
||||
[QQ Group](https://qm.qq.com/q/VfjAq5HIMS)
|
||||
|
||||
[Telegram Link](https://t.me/+nLZEnpne-pQ1OWFl)
|
||||
|
||||
## 附加协议
|
||||
禁止未授权任何项目使用Core部分代码用于二次开发与分发
|
||||
|
||||
## 鸣谢名单
|
||||
感谢 [LLOneBot](https://github.com/LLOneBot/LLOneBot) 提供初始版本基础
|
||||
|
||||
感谢 [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持
|
||||
|
||||
---
|
||||
**任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**
|
||||
|
||||
## 使用许可
|
||||
|
||||
任何使用本仓库代码的地方,都应当严格遵守[本仓库开源许可](./LICENSE)。**此外,禁止任何项目未经授权二次分发或基于 [core](./src/core) 部分代码开发。**
|
||||
|
@@ -3,8 +3,8 @@
|
||||
"type": "extension",
|
||||
"name": "NapCat",
|
||||
"slug": "NapCat",
|
||||
"description": "OneBot v11 protocol implementation with NapCat logic",
|
||||
"version": "2.0.2",
|
||||
"description": "现代化的 OneBot 11 协议实现",
|
||||
"version": "2.0.20",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
@@ -30,4 +30,4 @@
|
||||
"main": "./liteloader.cjs",
|
||||
"preload": "./preload.cjs"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -2,7 +2,7 @@
|
||||
"name": "napcat",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "2.0.2",
|
||||
"version": "2.0.20",
|
||||
"scripts": {
|
||||
"build:framework": "vite build --mode framework",
|
||||
"build:shell": "vite build --mode shell",
|
||||
|
77
script/BootWay05_init.bat
Normal file
77
script/BootWay05_init.bat
Normal file
@@ -0,0 +1,77 @@
|
||||
@echo off
|
||||
REM Check if the script is running as administrator
|
||||
openfiles >nul 2>&1
|
||||
if %errorlevel% neq 0 (
|
||||
REM If not, restart the script in administrator mode
|
||||
echo Requesting administrator privileges...
|
||||
powershell -Command "Start-Process cmd -ArgumentList '/c %~f0 %*' -Verb RunAs"
|
||||
exit /b
|
||||
)
|
||||
|
||||
cd /d %~dp0
|
||||
|
||||
set currentPath=%cd%
|
||||
set currentPath=%currentPath:\=/%
|
||||
|
||||
REM Generate JavaScript code
|
||||
set "jsCode=(async () =^>await import('file:///%currentPath%/napcat.mjs'))();"
|
||||
|
||||
REM Save JavaScript code to a file
|
||||
echo %jsCode% > loadScript.js
|
||||
echo JavaScript code has been generated and saved to loadScript.js
|
||||
|
||||
REM Set NAPCAT_PATH environment variable to the address of loadScript.js in the current directory
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Get QQ path and cache it
|
||||
:loop_read
|
||||
for /f "tokens=2*" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\QQ" /v "UninstallString"') do (
|
||||
set "RetString=%%b"
|
||||
)
|
||||
|
||||
set "pathWithoutUninstall=%RetString:Uninstall.exe=%"
|
||||
|
||||
SET QQPath=%pathWithoutUninstall%QQ.exe
|
||||
echo %QQPath%>qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been cached to qq_path_cache.txt
|
||||
|
||||
REM Exit if QQ path is invalid
|
||||
if not exist "%QQpath%" (
|
||||
echo provided QQ path is invalid: %QQpath%
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
|
||||
REM Collect dbghelp.dll path and HASH information
|
||||
set QQdir=%~dp0
|
||||
set oldDllPath=%QQdir%dbghelp.dll
|
||||
set newDllPath=%currentPath%\dbghelp.dll
|
||||
|
||||
for /f "tokens=*" %%A in ('certutil -hashfile "%oldDllPath%" MD5') do (
|
||||
if not defined oldDllHash set oldDllHash=%%A
|
||||
)
|
||||
for /f "tokens=*" %%A in ('certutil -hashfile "%newDllPath%" MD5') do (
|
||||
if not defined newDllHash set newDllHash=%%A
|
||||
)
|
||||
|
||||
REM Compare the HASH of the old and new dbghelp.dll, and replace the old one if they are different
|
||||
if "%oldDllHash%" neq "%newDllHash%" (
|
||||
tasklist /fi "imagename eq QQ.exe" 2>nul | find /i "QQ.exe" >nul
|
||||
if %errorlevel% equ 0 (
|
||||
REM If the file is in use, prompt the user to close QQ
|
||||
echo dbghelp.dll is in use, please close QQ first.
|
||||
) else (
|
||||
copy /y "%newDllPath%" "%oldDllPath%"
|
||||
if %errorlevel% neq 0 (
|
||||
echo Copy dbghelp.dll failed, please check and try again.
|
||||
pause
|
||||
exit /b
|
||||
) else (
|
||||
echo dbghelp.dll has been updated.
|
||||
echo Please run BootWay05_run.bat to start QQ.
|
||||
echo If you update QQ in the future, please run BootWay05_init.bat again.
|
||||
pause
|
||||
exit /b
|
||||
)
|
||||
)
|
||||
)
|
10
script/BootWay05_run.bat
Normal file
10
script/BootWay05_run.bat
Normal file
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
set /p QQPath=<qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been read from qq_path_cache.txt
|
||||
echo If failed to start QQ, please try running this script in administrator mode.
|
||||
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Launch QQ.exe with params provided
|
||||
|
||||
"%QQPath%" --enable-logging %*
|
13
script/BootWay05_run.utf8.bat
Normal file
13
script/BootWay05_run.utf8.bat
Normal file
@@ -0,0 +1,13 @@
|
||||
@echo off
|
||||
|
||||
chcp 65001
|
||||
|
||||
set /p QQPath=<qq_path_cache.txt
|
||||
echo QQ path %QQPath% has been read from qq_path_cache.txt
|
||||
echo If failed to start QQ, please try running this script in administrator mode.
|
||||
|
||||
set NAPCAT_PATH=%cd%\loadScript.js
|
||||
|
||||
REM Launch QQ.exe with params provided
|
||||
|
||||
"%QQPath%" --enable-logging %*
|
@@ -2,7 +2,7 @@ import path, { dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import fs from 'fs';
|
||||
|
||||
export const napcat_version = '2.0.2';
|
||||
export const napcat_version = '2.0.20';
|
||||
|
||||
export class NapCatPathWrapper {
|
||||
binaryPath: string;
|
||||
|
@@ -2,6 +2,7 @@ import log4js, { Configuration } from 'log4js';
|
||||
import { truncateString } from '@/common/utils/helper';
|
||||
import path from 'node:path';
|
||||
import chalk from 'chalk';
|
||||
import { AtType, ChatType, ElementType, ElementWrapper, RawMessage, SelfInfo } from '@/core';
|
||||
|
||||
export enum LogLevel {
|
||||
DEBUG = 'debug',
|
||||
@@ -135,4 +136,104 @@ export class LogWrapper {
|
||||
logFatal(...args: any[]) {
|
||||
this._log(LogLevel.FATAL, ...args);
|
||||
}
|
||||
|
||||
logMessage(msg: RawMessage, selfInfo: SelfInfo) {
|
||||
const isSelfSent = msg.senderUin === selfInfo.uin;
|
||||
this.log(`${
|
||||
isSelfSent ? '发送 ->' : '接收 <-'
|
||||
} ${rawMessageToText(msg)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function rawMessageToText(msg: RawMessage, recursiveLevel = 0): string {
|
||||
if (recursiveLevel > 2) {
|
||||
return '...';
|
||||
}
|
||||
|
||||
const tokens: string[] = [];
|
||||
|
||||
if (msg.chatType == ChatType.friend) {
|
||||
tokens.push(`私聊 (${msg.peerUin})`);
|
||||
} else if (msg.chatType == ChatType.group) {
|
||||
tokens.push(`群聊 (群 ${msg.peerUin} 的 ${msg.senderUin})`);
|
||||
} else if (msg.chatType == ChatType.chatDevice) {
|
||||
tokens.push('移动设备');
|
||||
} else /* temp */ {
|
||||
tokens.push(`临时消息 (${msg.peerUin})`);
|
||||
}
|
||||
|
||||
// message content
|
||||
|
||||
function msgElementToText(element: ElementWrapper) {
|
||||
if (element.textElement) {
|
||||
if (element.textElement.atType === AtType.notAt) {
|
||||
return element.textElement.content;
|
||||
} else if (element.textElement.atType === AtType.atAll) {
|
||||
return `@全体成员`;
|
||||
} else if (element.textElement.atType === AtType.atUser) {
|
||||
return `${element.textElement.content} (${element.textElement.atUid})`;
|
||||
}
|
||||
}
|
||||
|
||||
if (element.replyElement) {
|
||||
const recordMsgOrNull = msg.records.find(
|
||||
record => element.replyElement!.sourceMsgIdInRecords === record.msgId
|
||||
);
|
||||
return `[回复消息 ${
|
||||
recordMsgOrNull &&
|
||||
recordMsgOrNull.peerUin != '284840486' // 非转发消息; 否则定位不到
|
||||
?
|
||||
rawMessageToText(recordMsgOrNull, recursiveLevel + 1) :
|
||||
`未找到消息记录 (MsgId = ${element.replyElement.sourceMsgIdInRecords})`
|
||||
}]`;
|
||||
}
|
||||
|
||||
if (element.picElement) {
|
||||
return `[图片 ${element.picElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.fileElement) {
|
||||
return `[文件 ${element.fileElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.videoElement) {
|
||||
return `[视频 ${element.videoElement.fileName}]`;
|
||||
}
|
||||
|
||||
if (element.pttElement) {
|
||||
return `[语音 ${element.pttElement.duration}s]`;
|
||||
}
|
||||
|
||||
if (element.arkElement) {
|
||||
return `[卡片消息 ${element.arkElement.bytesData}]`;
|
||||
}
|
||||
|
||||
if (element.faceElement) {
|
||||
return `[表情 ${element.faceElement.faceText ?? ''}]`;
|
||||
}
|
||||
|
||||
if (element.marketFaceElement) {
|
||||
return `[商城表情 ${element.marketFaceElement.faceName}]`;
|
||||
}
|
||||
|
||||
if (element.markdownElement) {
|
||||
return `[Markdown ${element.markdownElement.content}]`;
|
||||
}
|
||||
|
||||
if (element.multiForwardMsgElement) {
|
||||
return `[转发消息]`;
|
||||
}
|
||||
|
||||
if (element.elementType === ElementType.GreyTip) {
|
||||
return `[灰条消息]`; // TODO: resolve the text
|
||||
}
|
||||
|
||||
return `[未实现 (ElementType = ${element.elementType})]`;
|
||||
}
|
||||
|
||||
for (const element of msg.elements) {
|
||||
tokens.push(msgElementToText(element));
|
||||
}
|
||||
|
||||
return tokens.join(' ');
|
||||
}
|
||||
|
@@ -117,31 +117,31 @@ export class NTQQFileApi {
|
||||
filePath: string
|
||||
}) => Promise<unknown>,
|
||||
(fileTransNotifyInfo: OnRichMediaDownloadCompleteParams) => void
|
||||
>(
|
||||
'NodeIKernelMsgService/downloadRichMedia',
|
||||
'NodeIKernelMsgListener/onRichMediaDownloadComplete',
|
||||
1,
|
||||
timeout,
|
||||
(arg: OnRichMediaDownloadCompleteParams) => {
|
||||
if (arg.msgId === msgId) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
{
|
||||
fileModelId: '0',
|
||||
downloadSourceType: 0,
|
||||
triggerType: 1,
|
||||
msgId: msgId,
|
||||
chatType: chatType,
|
||||
peerUid: peerUid,
|
||||
elementId: elementId,
|
||||
thumbSize: 0,
|
||||
downloadType: 1,
|
||||
filePath: thumbPath,
|
||||
},
|
||||
);
|
||||
let msg = await this.core.apis.MsgApi.getMsgsByMsgId({
|
||||
>(
|
||||
'NodeIKernelMsgService/downloadRichMedia',
|
||||
'NodeIKernelMsgListener/onRichMediaDownloadComplete',
|
||||
1,
|
||||
timeout,
|
||||
(arg: OnRichMediaDownloadCompleteParams) => {
|
||||
if (arg.msgId === msgId) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
{
|
||||
fileModelId: '0',
|
||||
downloadSourceType: 0,
|
||||
triggerType: 1,
|
||||
msgId: msgId,
|
||||
chatType: chatType,
|
||||
peerUid: peerUid,
|
||||
elementId: elementId,
|
||||
thumbSize: 0,
|
||||
downloadType: 1,
|
||||
filePath: thumbPath,
|
||||
},
|
||||
);
|
||||
const msg = await this.core.apis.MsgApi.getMsgsByMsgId({
|
||||
guildId: '',
|
||||
chatType: chatType,
|
||||
peerUid: peerUid,
|
||||
@@ -150,13 +150,13 @@ export class NTQQFileApi {
|
||||
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) {
|
||||
//失败则就乱来 Todo
|
||||
return data[1].filePath;
|
||||
}
|
||||
//从原始消息获取文件路径
|
||||
let filePath =
|
||||
const filePath =
|
||||
FileElements?.fileElement?.filePath ||
|
||||
FileElements?.pttElement?.filePath ||
|
||||
FileElements?.videoElement?.filePath ||
|
||||
@@ -280,10 +280,10 @@ export class NTQQFileApi {
|
||||
let id = '';
|
||||
const Listener = this.core.eventWrapper.RegisterListen<(params: OnListener) => void>
|
||||
(
|
||||
'NodeIKernelSearchListener/onSearchFileKeywordsResult',
|
||||
1,
|
||||
20000,
|
||||
(params) => id !== '' && params.searchId == id,
|
||||
'NodeIKernelSearchListener/onSearchFileKeywordsResult',
|
||||
1,
|
||||
20000,
|
||||
(params) => id !== '' && params.searchId == id,
|
||||
);
|
||||
id = await Event!(keys, 12);
|
||||
const [ret] = (await Listener);
|
||||
|
@@ -83,12 +83,12 @@ export class NTQQFriendApi {
|
||||
async getFriends(forced = false): Promise<User[]> {
|
||||
const [_retData, _BuddyArg] = await this.core.eventWrapper.CallNormalEvent<(force: boolean) => Promise<any>, (arg: OnBuddyChangeParams) => void>
|
||||
(
|
||||
'NodeIKernelBuddyService/getBuddyList',
|
||||
'NodeIKernelBuddyListener/onBuddyListChange',
|
||||
1,
|
||||
5000,
|
||||
() => true,
|
||||
forced,
|
||||
'NodeIKernelBuddyService/getBuddyList',
|
||||
'NodeIKernelBuddyListener/onBuddyListChange',
|
||||
1,
|
||||
5000,
|
||||
() => true,
|
||||
forced,
|
||||
);
|
||||
const friends: User[] = [];
|
||||
for (const categoryItem of _BuddyArg) {
|
||||
|
@@ -103,18 +103,18 @@ export class NTQQMsgApi {
|
||||
const data = await this.core.eventWrapper.CallNormalEvent<
|
||||
(GroupCode: string, params: GetFileListParam) => Promise<unknown>,
|
||||
(groupFileListResult: onGroupFileInfoUpdateParamType) => void
|
||||
>(
|
||||
'NodeIKernelRichMediaService/getGroupFileList',
|
||||
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
|
||||
1,
|
||||
5000,
|
||||
(groupFileListResult: onGroupFileInfoUpdateParamType) => {
|
||||
>(
|
||||
'NodeIKernelRichMediaService/getGroupFileList',
|
||||
'NodeIKernelMsgListener/onGroupFileInfoUpdate',
|
||||
1,
|
||||
5000,
|
||||
(groupFileListResult: onGroupFileInfoUpdateParamType) => {
|
||||
//Developer Mlikiowa Todo: 此处有问题 无法判断是否成功
|
||||
return true;
|
||||
},
|
||||
GroupCode,
|
||||
params,
|
||||
);
|
||||
return true;
|
||||
},
|
||||
GroupCode,
|
||||
params,
|
||||
);
|
||||
return data[1].item;
|
||||
}
|
||||
|
||||
@@ -155,24 +155,24 @@ export class NTQQMsgApi {
|
||||
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;
|
||||
>(
|
||||
'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(),
|
||||
);
|
||||
return false;
|
||||
},
|
||||
msgId,
|
||||
peer,
|
||||
msgElements,
|
||||
new Map(),
|
||||
);
|
||||
const retMsg = data[1].find(msgRecord => {
|
||||
if (msgRecord.msgId === msgId) {
|
||||
return true;
|
||||
@@ -186,7 +186,7 @@ export class NTQQMsgApi {
|
||||
}
|
||||
async PrepareTempChat(toUserUid: string, GroupCode: string, nickname: string) {
|
||||
//By Jadx/Ida Mlikiowa
|
||||
let TempGameSession = {
|
||||
const TempGameSession = {
|
||||
nickname: "",
|
||||
gameAppId: "",
|
||||
selfTinyId: "",
|
||||
@@ -210,7 +210,7 @@ export class NTQQMsgApi {
|
||||
async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = true, timeout = 10000) {
|
||||
//唉? !我有个想法
|
||||
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) {
|
||||
await this.PrepareTempChat(peer.peerUid, peer.guildId, member.nick);
|
||||
}
|
||||
@@ -220,24 +220,24 @@ export class NTQQMsgApi {
|
||||
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.guildId === msgId && msgRecord.sendStatus === 2) {
|
||||
return true;
|
||||
>(
|
||||
'NodeIKernelMsgService/sendMsg',
|
||||
'NodeIKernelMsgListener/onMsgInfoListUpdate',
|
||||
1,
|
||||
timeout,
|
||||
(msgRecords: RawMessage[]) => {
|
||||
for (const msgRecord of msgRecords) {
|
||||
if (msgRecord.guildId === msgId && msgRecord.sendStatus === 2) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
'0',
|
||||
peer,
|
||||
msgElements,
|
||||
new Map(),
|
||||
);
|
||||
return false;
|
||||
},
|
||||
'0',
|
||||
peer,
|
||||
msgElements,
|
||||
new Map(),
|
||||
);
|
||||
const retMsg = data[1].find(msgRecord => {
|
||||
if (msgRecord.guildId === msgId) {
|
||||
return true;
|
||||
@@ -272,31 +272,31 @@ export class NTQQMsgApi {
|
||||
const data = await this.core.eventWrapper.CallNormalEvent<
|
||||
(msgInfo: typeof msgInfos, srcPeer: Peer, destPeer: Peer, comment: Array<any>, attr: Map<any, any>) => Promise<unknown>,
|
||||
(msgList: RawMessage[]) => void
|
||||
>(
|
||||
'NodeIKernelMsgService/multiForwardMsgWithComment',
|
||||
'NodeIKernelMsgListener/onMsgInfoListUpdate',
|
||||
1,
|
||||
5000,
|
||||
(msgRecords: RawMessage[]) => {
|
||||
for (const msgRecord of msgRecords) {
|
||||
if (msgRecord.peerUid == destPeer.peerUid && msgRecord.senderUid == this.core.selfInfo.uid) {
|
||||
return true;
|
||||
>(
|
||||
'NodeIKernelMsgService/multiForwardMsgWithComment',
|
||||
'NodeIKernelMsgListener/onMsgInfoListUpdate',
|
||||
1,
|
||||
5000,
|
||||
(msgRecords: RawMessage[]) => {
|
||||
for (const msgRecord of msgRecords) {
|
||||
if (msgRecord.peerUid == destPeer.peerUid && msgRecord.senderUid == this.core.selfInfo.uid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
msgInfos,
|
||||
srcPeer,
|
||||
destPeer,
|
||||
[],
|
||||
new Map(),
|
||||
);
|
||||
return false;
|
||||
},
|
||||
msgInfos,
|
||||
srcPeer,
|
||||
destPeer,
|
||||
[],
|
||||
new Map(),
|
||||
);
|
||||
for (const msg of data[1]) {
|
||||
const arkElement = msg.elements.find(ele => ele.arkElement);
|
||||
if (!arkElement) {
|
||||
continue;
|
||||
}
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData);
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement?.bytesData || "");
|
||||
if (forwardData.app != 'com.tencent.multimsg') {
|
||||
continue;
|
||||
}
|
||||
|
@@ -155,16 +155,10 @@ export class NTQQUserApi {
|
||||
//需要异常处理
|
||||
async getCookies(domain: string) {
|
||||
const ClientKeyData = await this.forceFetchClientKey();
|
||||
const requestUrl = `https://ssl.ptlogin2.qq.com/jump?${
|
||||
new URLSearchParams({
|
||||
ptlang: '1033',
|
||||
clientuin: this.core.selfInfo.uin,
|
||||
clientkey: ClientKeyData.clientKey,
|
||||
u1: `https://user.qzone.qq.com/${this.core.selfInfo.uin}/infocenter`,
|
||||
keyindex: '19',
|
||||
})
|
||||
}`;
|
||||
return await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + this.core.selfInfo.uin +
|
||||
'&clientkey=' + ClientKeyData.clientKey + '&u1=https%3A%2F%2F' + domain + '%2F' + this.core.selfInfo.uin + '%2Finfocenter&keyindex=19%27';
|
||||
const cookies: { [key: string]: string; } = await RequestUtil.HttpsGetCookies(requestUrl);
|
||||
return cookies;
|
||||
}
|
||||
|
||||
async getPSkey(domainList: string[]) {
|
||||
|
@@ -4,7 +4,7 @@ import fs from 'node:fs';
|
||||
import { InstanceContext } from './wrapper';
|
||||
import { proxiedListenerOf } from '@/common/utils/proxy-handler';
|
||||
import { GroupListener, MsgListener, ProfileListener } from './listeners';
|
||||
import { GroupMember, SelfInfo, SelfStatusInfo } from './entities';
|
||||
import { GroupMember, SelfInfo } from './entities';
|
||||
import { LegacyNTEventWrapper } from '@/common/framework/event-legacy';
|
||||
import { NTQQFileApi, NTQQFriendApi, NTQQGroupApi, NTQQMsgApi, NTQQSystemApi, NTQQUserApi, NTQQWebApi } from './apis';
|
||||
import os from 'node:os';
|
||||
@@ -90,8 +90,8 @@ export class NapCatCore {
|
||||
// Renamed from 'InitDataListener'
|
||||
async initNapCatCoreListeners() {
|
||||
const msgListener = new MsgListener();
|
||||
msgListener.onRecvMsg = (msg) => {
|
||||
//console.log('RecvMsg', msg);
|
||||
msgListener.onRecvMsg = (msgs) => {
|
||||
msgs.forEach(msg => this.context.logger.logMessage(msg, this.selfInfo));
|
||||
};
|
||||
//await sleep(2500);
|
||||
this.context.session.getMsgService().addKernelMsgListener(
|
||||
@@ -104,7 +104,7 @@ export class NapCatCore {
|
||||
Object.assign(this.selfInfo, profile);
|
||||
}
|
||||
};
|
||||
profileListener.onSelfStatusChanged = (Info: SelfStatusInfo) => {
|
||||
profileListener.onSelfStatusChanged = (/* Info: SelfStatusInfo */) => {
|
||||
// if (Info.status == 20) {
|
||||
// log("账号状态变更为离线")
|
||||
// }
|
||||
@@ -128,12 +128,12 @@ export class NapCatCore {
|
||||
// 获取群成员
|
||||
}
|
||||
const sceneId = this.context.session.getGroupService().createMemberListScene(g.groupCode, 'groupMemberList_MainWindow');
|
||||
this.context.session.getGroupService().getNextMemberList(sceneId!, undefined, 3000).then(r => {
|
||||
this.context.session.getGroupService().getNextMemberList(sceneId!, undefined, 3000).then( /* r => {
|
||||
// console.log(`get group ${g.groupCode} members`, r);
|
||||
// r.result.infos.forEach(member => {
|
||||
// });
|
||||
// groupMembers.set(g.groupCode, r.result.infos);
|
||||
});
|
||||
} */);
|
||||
});
|
||||
};
|
||||
groupListener.onMemberListChange = (arg) => {
|
||||
|
@@ -26,36 +26,70 @@ export interface GetFileListParam {
|
||||
|
||||
export enum ElementType {
|
||||
UNKNOWN = 0,
|
||||
|
||||
TEXT = 1,
|
||||
|
||||
PIC = 2,
|
||||
|
||||
FILE = 3,
|
||||
|
||||
PTT = 4,
|
||||
|
||||
VIDEO = 5,
|
||||
|
||||
FACE = 6,
|
||||
|
||||
REPLY = 7,
|
||||
|
||||
WALLET = 9,
|
||||
GreyTip = 8,//Poke别叫戳一搓了 官方名字拍一拍 戳一戳是另一个名字
|
||||
|
||||
/**
|
||||
* “小灰条”,包括拍一拍 (Poke)、撤回提示等
|
||||
*/
|
||||
GreyTip = 8,
|
||||
|
||||
ARK = 10,
|
||||
|
||||
MFACE = 11,
|
||||
|
||||
LIVEGIFT = 12,
|
||||
|
||||
STRUCTLONGMSG = 13,
|
||||
|
||||
MARKDOWN = 14,
|
||||
|
||||
GIPHY = 15,
|
||||
|
||||
MULTIFORWARD = 16,
|
||||
|
||||
INLINEKEYBOARD = 17,
|
||||
|
||||
INTEXTGIFT = 18,
|
||||
|
||||
CALENDAR = 19,
|
||||
|
||||
YOLOGAMERESULT = 20,
|
||||
|
||||
AVRECORD = 21,
|
||||
|
||||
FEED = 22,
|
||||
|
||||
TOFURECORD = 23,
|
||||
|
||||
ACEBUBBLE = 24,
|
||||
|
||||
ACTIVITY = 25,
|
||||
|
||||
TOFU = 26,
|
||||
|
||||
FACEBUBBLE = 27,
|
||||
|
||||
SHARELOCATION = 28,
|
||||
|
||||
TASKTOPMSG = 29,
|
||||
|
||||
RECOMMENDEDMSG = 43,
|
||||
|
||||
ACTIONBAR = 44
|
||||
}
|
||||
|
||||
@@ -844,56 +878,142 @@ export enum NTSubMsgType {
|
||||
}
|
||||
export interface RawMessage {
|
||||
parentMsgPeer: Peer;
|
||||
parentMsgIdList: string[];
|
||||
id?: number;//扩展字段 用于处理OB11 ID
|
||||
guildId: string;
|
||||
msgRandom: string;
|
||||
|
||||
parentMsgIdList: string[];
|
||||
|
||||
/**
|
||||
* 扩展字段,与 Ob11 msg ID 有关
|
||||
*/
|
||||
id?: number;
|
||||
|
||||
guildId: string;
|
||||
|
||||
msgRandom: string;
|
||||
|
||||
msgId: string;
|
||||
|
||||
// 时间戳,秒
|
||||
/**
|
||||
* 消息时间戳(秒)
|
||||
*/
|
||||
msgTime: string;
|
||||
|
||||
msgSeq: string;
|
||||
|
||||
msgType: NTMsgType;
|
||||
|
||||
subMsgType: NTSubMsgType;
|
||||
|
||||
senderUid: string;
|
||||
senderUin: string; // 发送者QQ号
|
||||
peerUid: string; // 群号 或者 QQ uid
|
||||
peerUin: string; // 群号 或者 发送者QQ号
|
||||
|
||||
/**
|
||||
* 发送者 QQ 号
|
||||
*/
|
||||
senderUin: string;
|
||||
|
||||
/**
|
||||
* 群号 / 用户 UID
|
||||
*/
|
||||
peerUid: string;
|
||||
|
||||
/**
|
||||
* 群号 / 用户 QQ 号
|
||||
*/
|
||||
peerUin: string;
|
||||
|
||||
/**
|
||||
* 发送者昵称(如果是好友消息)
|
||||
*/
|
||||
sendNickName: string;
|
||||
sendMemberName?: string; // 发送者群名片
|
||||
|
||||
/**
|
||||
* 发送者群名片(如果是群消息)
|
||||
*/
|
||||
sendMemberName?: string;
|
||||
|
||||
chatType: ChatType;
|
||||
sendStatus?: number; // 消息状态,别人发的2是已撤回,自己发的2是已发送
|
||||
recallTime: string; // 撤回时间, "0"是没有撤回
|
||||
|
||||
/**
|
||||
* 消息状态,别人发的 2 是已撤回,自己发的 2 是已发送
|
||||
*/
|
||||
sendStatus?: number;
|
||||
|
||||
/**
|
||||
* 撤回时间,"0" 是没有撤回
|
||||
*/
|
||||
recallTime: string;
|
||||
|
||||
records: RawMessage[];
|
||||
elements: {
|
||||
elementId: string;
|
||||
elementType: ElementType;
|
||||
replyElement: {
|
||||
sourceMsgIdInRecords: string;
|
||||
senderUid: string; // 原消息发送者QQ号
|
||||
sourceMsgIsIncPic: boolean; // 原消息是否有图片
|
||||
sourceMsgText: string;
|
||||
replayMsgSeq: string; // 源消息的msgSeq,可以通过这个找到源消息的msgId
|
||||
};
|
||||
textElement: {
|
||||
atType: AtType;
|
||||
atUid: string; // QQ号
|
||||
content: string;
|
||||
atNtUid: string; // uid号
|
||||
};
|
||||
picElement: PicElement;
|
||||
pttElement: PttElement;
|
||||
arkElement: ArkElement;
|
||||
grayTipElement: GrayTipElement;
|
||||
faceElement: FaceElement;
|
||||
videoElement: VideoElement;
|
||||
fileElement: FileElement;
|
||||
marketFaceElement: MarketFaceElement;
|
||||
inlineKeyboardElement: InlineKeyboardElement;
|
||||
markdownElement: MarkdownElement;
|
||||
multiForwardMsgElement: MultiForwardMsgElement;
|
||||
}[];
|
||||
|
||||
elements: ElementWrapper[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 并非原生接口类型,故以 type 包装
|
||||
*/
|
||||
export type ElementWrapper = {
|
||||
elementId: string;
|
||||
|
||||
elementType: ElementType;
|
||||
|
||||
replyElement?: {
|
||||
sourceMsgIdInRecords: string;
|
||||
|
||||
/**
|
||||
* 源消息发送者 QQ 号
|
||||
*/
|
||||
senderUid: string;
|
||||
|
||||
/**
|
||||
* 源消息是否有图片
|
||||
*/
|
||||
sourceMsgIsIncPic: boolean;
|
||||
|
||||
/**
|
||||
* 源消息文本
|
||||
*/
|
||||
sourceMsgText: string;
|
||||
|
||||
/**
|
||||
* 源消息的 msgSeq,可以通过这个找到源消息的 msgId
|
||||
*/
|
||||
replayMsgSeq: string;
|
||||
};
|
||||
|
||||
textElement?: {
|
||||
atType: AtType;
|
||||
|
||||
/**
|
||||
* 被 @ 的 QQ 号
|
||||
*/
|
||||
atUid: string;
|
||||
|
||||
content: string;
|
||||
|
||||
/**
|
||||
* 被 @ 的 UID(从这里可以看出来 UID 的概念是 NT 才引入的)
|
||||
*/
|
||||
atNtUid: string;
|
||||
};
|
||||
|
||||
picElement?: PicElement;
|
||||
|
||||
pttElement?: PttElement;
|
||||
|
||||
arkElement?: ArkElement;
|
||||
|
||||
grayTipElement?: GrayTipElement;
|
||||
|
||||
faceElement?: FaceElement;
|
||||
|
||||
videoElement?: VideoElement;
|
||||
|
||||
fileElement?: FileElement;
|
||||
|
||||
marketFaceElement?: MarketFaceElement;
|
||||
|
||||
inlineKeyboardElement?: InlineKeyboardElement;
|
||||
|
||||
markdownElement?: MarkdownElement;
|
||||
|
||||
multiForwardMsgElement?: MultiForwardMsgElement;
|
||||
}
|
||||
|
@@ -87,13 +87,12 @@ function pollForNTInitializationCheck() {
|
||||
try {
|
||||
if (ntIsInitialized_Internal()) {
|
||||
isSolve = true;
|
||||
clearInterval(intervalRef);
|
||||
resolve(true);
|
||||
}
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
} finally {
|
||||
clearInterval(intervalRef);
|
||||
}
|
||||
}
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
@@ -113,7 +112,7 @@ async function fetchServices(timeout = 10000) {
|
||||
}),
|
||||
]).then(result => result ?
|
||||
{ wrapperSession, wrapperNodeApi, wrapperLoginService } :
|
||||
Promise.reject(),
|
||||
Promise.reject("fetchServices Timeout!"),
|
||||
);
|
||||
}
|
||||
let getWebUiUrlFunc = undefined;
|
||||
|
@@ -13,7 +13,7 @@ import { NapCatOneBot11Adapter } from '@/onebot';
|
||||
|
||||
//Framework ES入口文件
|
||||
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;
|
||||
}
|
||||
export async function NCoreInitFramework(
|
||||
|
@@ -1,14 +1,38 @@
|
||||
|
||||
export const onSettingWindowCreated = async (view) => {
|
||||
view.style.width = "100%";
|
||||
view.style.height = "100%";
|
||||
//添加iframe
|
||||
const iframe = document.createElement("iframe");
|
||||
iframe.src = await window.napcat.getWebUiUrl();
|
||||
iframe.width = "100%";
|
||||
iframe.height = "100%";
|
||||
iframe.style.border = "none";
|
||||
//去掉iframe滚动条
|
||||
//iframe.scrolling = "no";
|
||||
//有滚动条何尝不是一种美
|
||||
view.appendChild(iframe);
|
||||
|
||||
// view.style.width = "100%";
|
||||
// view.style.height = "100%";
|
||||
// //添加iframe
|
||||
// const iframe = document.createElement("iframe");
|
||||
// iframe.src = await window.napcat.getWebUiUrl();
|
||||
// iframe.width = "100%";
|
||||
// iframe.height = "100%";
|
||||
// iframe.style.border = "none";
|
||||
// //去掉iframe滚动条
|
||||
// //iframe.scrolling = "no";
|
||||
// //有滚动条何尝不是一种美
|
||||
// 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;
|
||||
};
|
@@ -6,14 +6,9 @@ export class GetFriendWithCategory extends BaseAction<void, any> {
|
||||
actionName = ActionName.GetFriendsWithCategory;
|
||||
|
||||
async _handle(payload: void) {
|
||||
if (this.CoreContext.context.basicInfoWrapper.requireMinNTQQBuild('26702')) {
|
||||
//全新逻辑
|
||||
return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({
|
||||
...category,
|
||||
buddyList: OB11Constructor.friendsV2(category.buddyList),
|
||||
}));
|
||||
} else {
|
||||
throw new Error('this ntqq version not support, must be 26702 or later');
|
||||
}
|
||||
return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({
|
||||
...category,
|
||||
buddyList: OB11Constructor.friendsV2(category.buddyList),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
@@ -5,7 +5,6 @@ export class GetRobotUinRange extends BaseAction<void, Array<any>> {
|
||||
actionName = ActionName.GetRobotUinRange;
|
||||
|
||||
async _handle(payload: void) {
|
||||
// console.log(await NTQQUserApi.getRobotUinRange());
|
||||
const NTQQUserApi = this.CoreContext.apis.UserApi;
|
||||
return await NTQQUserApi.getRobotUinRange();
|
||||
}
|
||||
|
@@ -28,19 +28,6 @@ const GetFileBase_PayloadSchema = {
|
||||
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
||||
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> {
|
||||
const NTQQFriendApi = this.CoreContext.apis.FriendApi;
|
||||
const NTQQUserApi = this.CoreContext.apis.UserApi;
|
||||
@@ -92,7 +79,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
||||
file_size: fileSize,
|
||||
file_name: fileName,
|
||||
};
|
||||
if (true/*enableLocalFile2Url*/) {
|
||||
if (true/*enableLocalFile2Url*/ && downloadPath) {
|
||||
try {
|
||||
res.base64 = await fs.readFile(downloadPath, 'base64');
|
||||
} catch (e) {
|
||||
@@ -132,7 +119,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
||||
file_size: NTSearchNameResult[0].fileSize.toString(),
|
||||
file_name: NTSearchNameResult[0].fileName,
|
||||
};
|
||||
if (true/*enableLocalFile2Url*/) {
|
||||
if (true/*enableLocalFile2Url*/ && downloadPath) {
|
||||
try {
|
||||
res.base64 = await fs.readFile(downloadPath, 'base64');
|
||||
} catch (e) {
|
||||
|
@@ -39,15 +39,16 @@ export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
|
||||
throw Error('找不到相关的聊天记录' + data?.errMsg);
|
||||
}
|
||||
const msgList = data.msgList;
|
||||
const messages = await Promise.all(msgList.map(async msg => {
|
||||
const resMsg = await OB11Constructor.message(this.CoreContext, msg, 'array');
|
||||
const messages = (await Promise.all(msgList.map(async msg => {
|
||||
const resMsg = await OB11Constructor.message(this.CoreContext, this.OneBotContext, msg);
|
||||
if (!resMsg) return;
|
||||
resMsg.message_id = MessageUnique.createMsg({
|
||||
guildId: '',
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
}, msg.msgId)!;
|
||||
return resMsg;
|
||||
}));
|
||||
}))).filter(msg => !!msg);
|
||||
messages.map(msg => {
|
||||
(<OB11ForwardMessage>msg).content = msg.message;
|
||||
delete (<any>msg).message;
|
||||
|
@@ -53,7 +53,7 @@ export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
|
||||
msg.id = MessageUnique.createMsg({ guildId: '', chatType: msg.chatType, peerUid: msg.peerUid }, msg.msgId);
|
||||
}));
|
||||
//转换消息
|
||||
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')));
|
||||
const ob11MsgList = (await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, this.OneBotContext, msg)))).filter(msg => !!msg);
|
||||
return { 'messages': ob11MsgList };
|
||||
}
|
||||
}
|
||||
|
@@ -48,7 +48,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Resp
|
||||
}));
|
||||
|
||||
//转换消息
|
||||
const ob11MsgList = await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, msg, 'array')));
|
||||
const ob11MsgList = (await Promise.all(msgList.map(msg => OB11Constructor.message(this.CoreContext, this.OneBotContext, msg)))).filter(msg => !!msg);
|
||||
return { 'messages': ob11MsgList };
|
||||
}
|
||||
}
|
||||
|
10
src/onebot/action/go-cqhttp/SetModelShow.ts
Normal file
10
src/onebot/action/go-cqhttp/SetModelShow.ts
Normal 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;
|
||||
}
|
||||
}
|
@@ -20,9 +20,7 @@ export default class DelEssenceMsg extends BaseAction<Payload, any> {
|
||||
async _handle(payload: Payload): Promise<any> {
|
||||
const NTQQGroupApi = this.CoreContext.apis.GroupApi;
|
||||
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
|
||||
if (!msg) {
|
||||
throw new Error('msg not found');
|
||||
}
|
||||
if (!msg) throw new Error('msg not found');
|
||||
return await NTQQGroupApi.removeGroupEssence(
|
||||
msg.Peer.peerUid,
|
||||
msg.MsgId,
|
||||
|
@@ -9,7 +9,7 @@ const SchemaData = {
|
||||
group_id: { type: ['number', 'string'] },
|
||||
pages: { type: 'number' },
|
||||
},
|
||||
required: ['group_id', 'pages'],
|
||||
required: ['group_id'],
|
||||
} as const satisfies JSONSchema;
|
||||
|
||||
type Payload = FromSchema<typeof SchemaData>;
|
||||
@@ -20,7 +20,7 @@ export class GetGroupEssence extends BaseAction<Payload, GroupEssenceMsgRet> {
|
||||
|
||||
async _handle(payload: Payload) {
|
||||
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) {
|
||||
throw new Error('获取失败');
|
||||
}
|
||||
|
@@ -69,7 +69,7 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Mlikiowa V2.0.2 Refactor Todo
|
||||
// Mlikiowa V2.0.20 Refactor Todo
|
||||
// retMember.last_sent_time = parseInt((await getGroupMember(payload.group_id.toString(), retMember.user_id))?.lastSpeakTime || date.toString());
|
||||
// retMember.join_time = parseInt((await getGroupMember(payload.group_id.toString(), retMember.user_id))?.joinTime || date.toString());
|
||||
}
|
||||
|
@@ -83,7 +83,7 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Mlikiowa V2.0.2 Refactor Todo
|
||||
// Mlikiowa V2.0.20 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());
|
||||
|
10
src/onebot/action/guild/GetGuildProfile.ts
Normal file
10
src/onebot/action/guild/GetGuildProfile.ts
Normal 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;
|
||||
}
|
||||
}
|
@@ -23,7 +23,7 @@ import GoCQHTTPGetStrangerInfo from './go-cqhttp/GetStrangerInfo';
|
||||
import SendLike from './user/SendLike';
|
||||
import SetGroupAddRequest from './group/SetGroupAddRequest';
|
||||
import SetGroupLeave from './group/SetGroupLeave';
|
||||
import GetGuildList from './group/GetGuildList';
|
||||
import GetGuildList from './guild/GetGuildList';
|
||||
import SetFriendAddRequest from './user/SetFriendAddRequest';
|
||||
import SetGroupWholeBan from './group/SetGroupWholeBan';
|
||||
import SetGroupName from './group/SetGroupName';
|
||||
@@ -76,6 +76,8 @@ import { FetchEmojiLike } from './extends/FetchEmojiLike';
|
||||
import { NapCatCore } from '@/core';
|
||||
|
||||
import { NapCatOneBot11Adapter } from '@/onebot';
|
||||
import GetGuildProfile from './guild/GetGuildProfile';
|
||||
import SetModelShow from './go-cqhttp/SetModelShow';
|
||||
|
||||
export type ActionMap = Map<string, BaseAction<any, any>>;
|
||||
|
||||
@@ -161,6 +163,8 @@ export function createActionMap(onebotContext: NapCatOneBot11Adapter, coreContex
|
||||
new SetGroupHeader(onebotContext, coreContext),
|
||||
new FetchCustomFace(onebotContext, coreContext),
|
||||
new GoCQHTTPUploadPrivateFile(onebotContext, coreContext),
|
||||
new GetGuildProfile(onebotContext, coreContext),
|
||||
new SetModelShow(onebotContext, coreContext),
|
||||
];
|
||||
const actionMap = new Map();
|
||||
for (const action of actionHandlers) {
|
||||
|
@@ -28,8 +28,8 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
|
||||
if (!payload.message_id) {
|
||||
throw Error('参数message_id不能为空');
|
||||
}
|
||||
const MsgShortId = await MessageUnique.getShortIdByMsgId(payload.message_id.toString());
|
||||
const msgIdWithPeer = await MessageUnique.getMsgIdAndPeerByShortId(MsgShortId || parseInt(payload.message_id.toString()));
|
||||
const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
|
||||
const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId || parseInt(payload.message_id.toString()));
|
||||
if (!msgIdWithPeer) {
|
||||
throw ('消息不存在');
|
||||
}
|
||||
@@ -37,7 +37,8 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
|
||||
const msg = await NTQQMsgApi.getMsgsByMsgId(
|
||||
peer,
|
||||
[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 {
|
||||
retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!;
|
||||
retMsg.message_seq = retMsg.message_id;
|
||||
|
@@ -56,8 +56,8 @@ const _handlers: {
|
||||
if (atQQ === 'all') return SendMsgElementConstructor.at(coreContext, atQQ, atQQ, AtType.atAll, '全体成员');
|
||||
|
||||
// then the qq is a group member
|
||||
// Mlikiowa V2.0.2 Refactor Todo
|
||||
const uid = await coreContext.apis.UserApi.getUidByUinV2(atQQ);
|
||||
// Mlikiowa V2.0.19 Refactor Todo
|
||||
const uid = await coreContext.apis.UserApi.getUidByUinV2(`${atQQ}`);
|
||||
if (!uid) throw new Error('Get Uid Error');
|
||||
return SendMsgElementConstructor.at(coreContext, atQQ, uid, AtType.atUser, '');
|
||||
},
|
||||
@@ -161,7 +161,7 @@ const _handlers: {
|
||||
} else {
|
||||
postData = data;
|
||||
}
|
||||
// Mlikiowa V2.0.2 Refactor Todo
|
||||
// Mlikiowa V2.0.19 Refactor Todo
|
||||
const signUrl = obContext.configLoader.configData.musicSignUrl;
|
||||
if (!signUrl) {
|
||||
if (data.type === 'qq') {
|
||||
|
@@ -105,6 +105,7 @@ async function createContext(coreContext: NapCatCore, payload: OB11PostSendMsg,
|
||||
return {
|
||||
chatType: isBuddy ? ChatType.friend : ChatType.temp,
|
||||
peerUid: Uid!,
|
||||
guildId: payload.group_id?.toString() || '',
|
||||
};
|
||||
}
|
||||
throw '请指定 group_id 或 user_id';
|
||||
|
@@ -104,5 +104,7 @@ export enum ActionName {
|
||||
FetchCustomFace = 'fetch_custom_face',
|
||||
GOCQHTTP_UploadPrivateFile = 'upload_private_file',
|
||||
TestApi01 = 'test_api_01',
|
||||
FetchEmojiLike = 'fetch_emoji_like'
|
||||
FetchEmojiLike = 'fetch_emoji_like',
|
||||
GetGuildProfile = "get_guild_service_profile",
|
||||
SetModelShow = "_set_model_show"
|
||||
}
|
||||
|
@@ -67,7 +67,7 @@ export class GetCookies extends BaseAction<Payload, Response> {
|
||||
const cookiesObject = await NTQQUserApi.getCookies(payload.domain);
|
||||
//把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
@@ -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]);
|
||||
if (FastMsg.msgList.length > 0) {
|
||||
//扩展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 {
|
||||
lastestMsg: lastestMsg,
|
||||
peerUin: t.peerUin,
|
||||
|
@@ -42,10 +42,18 @@ import { OB11BaseNoticeEvent } from '../event/notice/OB11BaseNoticeEvent';
|
||||
import { OB11GroupEssenceEvent } from '../event/notice/OB11GroupEssenceEvent';
|
||||
import { MessageUnique } from '@/common/utils/MessageUnique';
|
||||
import { NapCatCore } from '@/core';
|
||||
|
||||
import { NapCatOneBot11Adapter } from '..';
|
||||
|
||||
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 NTQQUserApi = core.apis.UserApi;
|
||||
const NTQQFileApi = core.apis.FileApi;
|
||||
@@ -75,8 +83,8 @@ export class OB11Constructor {
|
||||
resMsg.sub_type = 'normal'; // 这里go-cqhttp是group,而onebot11标准是normal, 蛋疼
|
||||
resMsg.group_id = parseInt(msg.peerUin);
|
||||
//直接去QQNative取
|
||||
const memberList = await NTQQGroupApi.getGroupMembers(msg.peerUin);
|
||||
const member = memberList.get(msg.senderUin!);
|
||||
let member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
|
||||
if (!member) member = await NTQQGroupApi.getGroupMember(msg.peerUin, msg.senderUin);
|
||||
if (member) {
|
||||
resMsg.sender.role = OB11Constructor.groupMemberRole(member.role);
|
||||
resMsg.sender.nickname = member.nick;
|
||||
@@ -141,7 +149,7 @@ export class OB11Constructor {
|
||||
message_data['type'] = OB11MessageDataType.reply;
|
||||
//log("收到回复消息", element.replyElement);
|
||||
try {
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element.replyElement.sourceMsgIdInRecords);
|
||||
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.replyElement?.sourceMsgIdInRecords);
|
||||
const peer = {
|
||||
chatType: msg.chatType,
|
||||
peerUid: msg.peerUid,
|
||||
@@ -342,7 +350,8 @@ export class OB11Constructor {
|
||||
MultiMsg.parentMsgPeer = ParentMsgPeer;
|
||||
MultiMsg.parentMsgIdList = msg.parentMsgIdList;
|
||||
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);
|
||||
//console.log("合并消息", msgList);
|
||||
}
|
||||
@@ -408,7 +417,7 @@ export class OB11Constructor {
|
||||
return;
|
||||
}
|
||||
//log("group msg", msg);
|
||||
// Mlikiowa V2.0.2 Refactor Todo
|
||||
// Mlikiowa V2.0.20 Refactor Todo
|
||||
// if (msg.senderUin && msg.senderUin !== '0') {
|
||||
// const member = await getGroupMember(msg.peerUid, msg.senderUin);
|
||||
// if (member && member.cardName !== msg.sendMemberName) {
|
||||
|
@@ -1,86 +0,0 @@
|
||||
import { Group, NapCatCore } from '@/core';
|
||||
import { OB11Message } from '@/onebot/types';
|
||||
import chalk from 'chalk';
|
||||
|
||||
const spSegColor = chalk.blue;// for special segment
|
||||
const spColor = chalk.cyan;// for special
|
||||
|
||||
// todo: 应该放到core去用RawMessage解析打印
|
||||
export async function logOB11Message(coreContext: NapCatCore, ob11Message: OB11Message) {
|
||||
const isSelfSent = ob11Message.sender.user_id.toString() === coreContext.selfInfo.uin;
|
||||
let prefix = '';
|
||||
let group: Group | undefined;
|
||||
if (isSelfSent) {
|
||||
prefix = '发送消息 ';
|
||||
if (ob11Message.message_type === 'private') {
|
||||
prefix += '给私聊 ';
|
||||
prefix += `${ob11Message.target_id}`;
|
||||
} else {
|
||||
prefix += '给群聊 ';
|
||||
}
|
||||
}
|
||||
if (ob11Message.message_type === 'group') {
|
||||
if (ob11Message.group_id == 284840486) {
|
||||
// group = await coreContext.ApiContext.GroupApi.getGroup(ob11Message.group_id!.toString());
|
||||
prefix += '转发消息[外部来源] ';
|
||||
} else {
|
||||
group = await coreContext.apis.GroupApi.getGroup(ob11Message.group_id!.toString());
|
||||
prefix += `群[${group?.groupName}(${ob11Message.group_id})] `;
|
||||
}
|
||||
}
|
||||
let msgChain: string;
|
||||
if (Array.isArray(ob11Message.message)) {
|
||||
const msgParts = [];
|
||||
for (const segment of ob11Message.message) {
|
||||
if (segment.type === 'text') {
|
||||
msgParts.push(segment.data.text);
|
||||
} else if (segment.type === 'at') {
|
||||
const groupMember = await coreContext.apis.GroupApi.getGroupMember(ob11Message.group_id!, segment.data.qq!);
|
||||
msgParts.push(spSegColor(`[@${groupMember?.cardName || groupMember?.nick}(${segment.data.qq})]`));
|
||||
} else if (segment.type === 'reply') {
|
||||
msgParts.push(spSegColor(`[回复消息|id:${segment.data.id}]`));
|
||||
} else if (segment.type === 'image') {
|
||||
msgParts.push(spSegColor(`[图片|${segment.data.url}]`));
|
||||
} else if (segment.type === 'face') {
|
||||
msgParts.push(spSegColor(`[表情|id:${segment.data.id}]`));
|
||||
} else if (segment.type === 'mface') {
|
||||
// @ts-expect-error 商城表情 url
|
||||
msgParts.push(spSegColor(`[商城表情|${segment.data.url}]`));
|
||||
} else if (segment.type === 'record') {
|
||||
msgParts.push(spSegColor(`[语音|${segment.data.file}]`));
|
||||
} else if (segment.type === 'file') {
|
||||
msgParts.push(spSegColor(`[文件|${segment.data.file}]`));
|
||||
} else if (segment.type === 'json') {
|
||||
msgParts.push(spSegColor(`[json|${JSON.stringify(segment.data)}]`));
|
||||
} else if (segment.type === 'markdown') {
|
||||
msgParts.push(spSegColor(`[markdown|${segment.data.content}]`));
|
||||
} else if (segment.type === 'video') {
|
||||
msgParts.push(spSegColor(`[视频|${segment.data.url}]`));
|
||||
} else if (segment.type === 'forward') {
|
||||
msgParts.push(spSegColor(`[转发|${segment.data.id}|消息开始]`));
|
||||
segment.data.content.forEach((msg) => {
|
||||
logOB11Message(coreContext, msg);
|
||||
});
|
||||
msgParts.push(spSegColor(`[转发|${segment.data.id}|消息结束]`));
|
||||
} else {
|
||||
msgParts.push(spSegColor(`[未实现|${JSON.stringify(segment)}]`));
|
||||
}
|
||||
}
|
||||
msgChain = msgParts.join(' ');
|
||||
} else {
|
||||
msgChain = ob11Message.message;
|
||||
}
|
||||
let msgString = `${prefix}${ob11Message.sender.nickname}(${ob11Message.sender.user_id}): ${msgChain}`;
|
||||
if (isSelfSent) {
|
||||
msgString = `${prefix}: ${msgChain}`;
|
||||
}
|
||||
coreContext.context.logger.log(msgString);
|
||||
}
|
||||
|
||||
export async function logOB11Notice(coreContext: NapCatCore, ob11Notice: any) {
|
||||
coreContext.context.logger.log(spColor('[Notice]'), ob11Notice);
|
||||
}
|
||||
|
||||
export async function logOB11Request(coreContext: NapCatCore, ob11Request: any) {
|
||||
coreContext.context.logger.log(spColor('[Request]'), ob11Request);
|
||||
}
|
@@ -25,7 +25,6 @@ import { WebUiDataRuntime } from '@/webui/src/helper/Data';
|
||||
import { OB11InputStatusEvent } from '@/onebot/event/notice/OB11InputStatusEvent';
|
||||
import { MessageUnique } from '@/common/utils/MessageUnique';
|
||||
import { OB11Constructor } from '@/onebot/helper/data';
|
||||
import { logOB11Message } from '@/onebot/helper/log';
|
||||
import { proxiedListenerOf } from '@/common/utils/proxy-handler';
|
||||
import { OB11FriendRequestEvent } from '@/onebot/event/request/OB11FriendRequest';
|
||||
import { OB11GroupAdminNoticeEvent } from '@/onebot/event/notice/OB11GroupAdminNoticeEvent';
|
||||
@@ -251,13 +250,12 @@ export class NapCatOneBot11Adapter {
|
||||
.catch(e => this.context.logger.logError('处理消息失败', e));
|
||||
|
||||
for (const msg of msgList.filter(e => e.senderUin == this.core.selfInfo.uin)) {
|
||||
// console.log(msg);
|
||||
if (!!msgIdSend.get(msg.msgId)) continue;
|
||||
msgIdSend.put(msg.msgId, true);
|
||||
if (msg.sendStatus == 2) {
|
||||
if (msg.sendStatus == 2 && !msgIdSend.get(msg.msgId)) {
|
||||
msgIdSend.put(msg.msgId, true);
|
||||
// 完成后再post
|
||||
OB11Constructor.message(this.core, msg, this.configLoader.configData.messagePostFormat)
|
||||
OB11Constructor.message(this.core, this, msg)
|
||||
.then((ob11Msg) => {
|
||||
if (!ob11Msg) return;
|
||||
ob11Msg.target_id = parseInt(msg.peerUin);
|
||||
if (this.configLoader.configData.reportSelfMessage) {
|
||||
msg.id = MessageUnique.createMsg({
|
||||
@@ -267,7 +265,7 @@ export class NapCatOneBot11Adapter {
|
||||
}, msg.msgId);
|
||||
this.emitMsg(msg);
|
||||
} else {
|
||||
logOB11Message(this.core, ob11Msg);
|
||||
// logOB11Message(this.core, ob11Msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -426,9 +424,10 @@ export class NapCatOneBot11Adapter {
|
||||
|
||||
private async emitMsg(message: RawMessage) {
|
||||
const { debug, reportSelfMessage, messagePostFormat } = this.configLoader.configData;
|
||||
this.context.logger.logDebug('收到新消息', message);
|
||||
OB11Constructor.message(this.core, message, messagePostFormat).then((ob11Msg) => {
|
||||
this.context.logger.logDebug('收到消息: ', ob11Msg);
|
||||
this.context.logger.logDebug('收到新消息 RawMessage', message);
|
||||
OB11Constructor.message(this.core, this, message, messagePostFormat).then((ob11Msg) => {
|
||||
if (!ob11Msg) return;
|
||||
this.context.logger.logDebug('转化为 OB11Message', ob11Msg);
|
||||
if (debug) {
|
||||
ob11Msg.raw = message;
|
||||
} else {
|
||||
@@ -436,8 +435,8 @@ export class NapCatOneBot11Adapter {
|
||||
return;
|
||||
}
|
||||
}
|
||||
logOB11Message(this.core, ob11Msg)
|
||||
.catch(e => this.context.logger.logError('logMessage error: ', e));
|
||||
// logOB11Message(this.core, ob11Msg)
|
||||
// .catch(e => this.context.logger.logError('logMessage error: ', e));
|
||||
const isSelfMsg = ob11Msg.user_id.toString() == this.core.selfInfo.uin;
|
||||
if (isSelfMsg && !reportSelfMessage) {
|
||||
return;
|
||||
@@ -484,6 +483,7 @@ export class NapCatOneBot11Adapter {
|
||||
let operatorId = message.senderUin;
|
||||
for (const element of message.elements) {
|
||||
const operatorUid = element.grayTipElement?.revokeElement.operatorUid;
|
||||
if (!operatorUid) return;
|
||||
const operator = await this.core.apis.GroupApi.getGroupMember(message.peerUin, operatorUid);
|
||||
operatorId = operator?.uin || message.senderUin;
|
||||
}
|
||||
|
@@ -6,6 +6,7 @@ import { ActionName } from '@/onebot/action/types';
|
||||
import { OB11Response } from '@/onebot/action/OB11Response';
|
||||
import { LogWrapper } from '@/common/utils/log';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
|
||||
|
||||
export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
isClosed: boolean = false;
|
||||
@@ -25,7 +26,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
|
||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
if (this.connection) {
|
||||
if (this.connection && this.connection.readyState === WebSocket.OPEN) {
|
||||
this.connection.send(JSON.stringify(event));
|
||||
}
|
||||
}
|
||||
@@ -69,6 +70,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
let isClosedByError = false;
|
||||
|
||||
this.connection = new WebSocket(this.url, {
|
||||
maxPayload: 1024 * 1024 * 1024,
|
||||
headers: {
|
||||
'X-Self-ID': this.coreContext.selfInfo.uin,
|
||||
'Authorization': `Bearer ${this.token}`,
|
||||
@@ -76,14 +78,22 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
'User-Agent': 'OneBot/11',
|
||||
},
|
||||
|
||||
});
|
||||
this.connection.on('open', () => {
|
||||
try {
|
||||
this.connectEvent(this.coreContext);
|
||||
} catch (e) {
|
||||
this.logger.logError('[OneBot] [WebSocket Client] 发送连接生命周期失败', e);
|
||||
}
|
||||
|
||||
});
|
||||
this.connection.on('message', (data) => {
|
||||
this.handleMessage(data);
|
||||
});
|
||||
this.connection.once('close', () => {
|
||||
if (!isClosedByError) {
|
||||
this.logger.logError(`反向WebSocket (${this.url}) 连接意外关闭`);
|
||||
this.logger.logError(`在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接意外关闭`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
if (!this.isClosed) {
|
||||
this.connection = null;
|
||||
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
|
||||
@@ -92,8 +102,8 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
});
|
||||
this.connection.on('error', (err) => {
|
||||
isClosedByError = true;
|
||||
this.logger.logError(`反向WebSocket (${this.url}) 连接错误`, err);
|
||||
this.logger.logError(`在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 反向WebSocket (${this.url}) 连接错误`, err);
|
||||
this.logger.logError(`[OneBot] [WebSocket Client] 在 ${Math.floor(this.reconnectIntervalInMillis / 1000)} 秒后尝试重新连接`);
|
||||
if (!this.isClosed) {
|
||||
this.connection = null;
|
||||
setTimeout(() => this.tryConnect(), this.reconnectIntervalInMillis);
|
||||
@@ -101,7 +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) {
|
||||
let receiveData: { action: ActionName, params?: any, echo?: any } = { action: ActionName.Unknown, params: {} };
|
||||
let echo = undefined;
|
||||
@@ -109,7 +125,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
try {
|
||||
receiveData = JSON.parse(message.toString());
|
||||
echo = receiveData.echo;
|
||||
this.logger.logDebug('收到正向Websocket消息', receiveData);
|
||||
this.logger.logDebug('[OneBot] [WebSocket Client] 收到正向Websocket消息', receiveData);
|
||||
} catch (e) {
|
||||
this.checkStateAndReply<any>(OB11Response.error('json解析失败,请检查数据格式', 1400, echo));
|
||||
}
|
||||
|
@@ -11,6 +11,7 @@ import { LogWrapper } from '@/common/utils/log';
|
||||
import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent';
|
||||
import { IncomingMessage } from 'http';
|
||||
import { ActionMap } from '@/onebot/action';
|
||||
import { LifeCycleSubType, OB11LifeCycleEvent } from '../event/meta/OB11LifeCycleEvent';
|
||||
|
||||
export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
wsServer: WebSocketServer;
|
||||
@@ -35,7 +36,8 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
this.logger = coreContext.context.logger;
|
||||
|
||||
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) => {
|
||||
if (!this.isOpen) {
|
||||
wsClient.close();
|
||||
@@ -43,9 +45,8 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
//鉴权
|
||||
this.authorize(token, wsClient, wsReq);
|
||||
|
||||
this.connectEvent(core, wsClient);
|
||||
wsClient.on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Client Error:', err.message));
|
||||
|
||||
wsClient.on('message', (message) => {
|
||||
this.handleMessage(wsClient, message).then().catch(this.logger.logError);
|
||||
});
|
||||
@@ -63,6 +64,14 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}).on('error', (err) => this.logger.log('[OneBot] [WebSocket Server] Server Error:', err.message));
|
||||
}
|
||||
|
||||
connectEvent(core: NapCatCore, wsClient: WebSocket) {
|
||||
try {
|
||||
this.checkStateAndReply<any>(new OB11LifeCycleEvent(core, LifeCycleSubType.CONNECT), wsClient);
|
||||
} catch (e) {
|
||||
this.logger.logError('[OneBot] [WebSocket Server] 发送生命周期失败', e);
|
||||
}
|
||||
}
|
||||
|
||||
onEvent<T extends OB11EmitEventContent>(event: T) {
|
||||
this.wsClientsMutex.runExclusive(async () => {
|
||||
this.wsClients.forEach((wsClient) => {
|
||||
@@ -82,7 +91,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
|
||||
}
|
||||
const addressInfo = this.wsServer.address();
|
||||
this.logger.log('[OneBot] [WebSocket Server] Server Started', typeof (addressInfo) === 'string' ? addressInfo : addressInfo?.address + ':' + addressInfo?.port);
|
||||
|
||||
|
||||
this.isOpen = true;
|
||||
this.registerHeartBeat();
|
||||
}
|
||||
|
@@ -168,20 +168,25 @@ export async function NCoreInitShell() {
|
||||
});
|
||||
});
|
||||
|
||||
if (quickLoginUin && historyLoginList.some(u => u.uin === quickLoginUin)) {
|
||||
logger.log('正在快速登录 ', quickLoginUin);
|
||||
setTimeout(() => {
|
||||
loginService.quickLoginWithUin(quickLoginUin)
|
||||
.then(result => {
|
||||
if (result.loginErrorInfo.errMsg) {
|
||||
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
|
||||
reject();
|
||||
}
|
||||
})
|
||||
.catch(e => reject(e));
|
||||
}, 1000);
|
||||
if (quickLoginUin) {
|
||||
if (historyLoginList.some(u => u.uin === quickLoginUin)) {
|
||||
logger.log('正在快速登录 ', quickLoginUin);
|
||||
setTimeout(() => {
|
||||
loginService.quickLoginWithUin(quickLoginUin)
|
||||
.then(result => {
|
||||
if (result.loginErrorInfo.errMsg) {
|
||||
logger.logError('快速登录错误:', result.loginErrorInfo.errMsg);
|
||||
loginService.getQRCodePicture();
|
||||
}
|
||||
})
|
||||
.catch();
|
||||
}, 1000);
|
||||
} else {
|
||||
logger.logError('快速登录失败,未找到该 QQ 历史登录记录,将使用二维码登录方式');
|
||||
loginService.getQRCodePicture();
|
||||
}
|
||||
} else {
|
||||
logger.log('没有 -q 指令指定快速登录,或未曾登录过这个 QQ,将使用二维码登录方式');
|
||||
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
|
||||
if (historyLoginList.length > 0) {
|
||||
logger.log(`可用于快速登录的 QQ:\n${
|
||||
historyLoginList
|
||||
|
@@ -19,7 +19,7 @@ export let webUiPathWrapper: NapCatPathWrapper;
|
||||
export async function InitWebUi(logger: LogWrapper, pathWrapper: NapCatPathWrapper) {
|
||||
webUiPathWrapper = pathWrapper;
|
||||
WebUiConfig = new WebUiConfigWrapper();
|
||||
let log = logger.log.bind(logger);
|
||||
const log = logger.log.bind(logger);
|
||||
const config = await WebUiConfig.GetWebUIConfig();
|
||||
if (config.port == 0) {
|
||||
log('[NapCat] [WebUi] Current WebUi is not run.');
|
||||
|
@@ -30,7 +30,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
SettingItem(
|
||||
'<span id="napcat-update-title">Napcat</span>',
|
||||
undefined,
|
||||
SettingButton('V2.0.2', 'napcat-update-button', 'secondary'),
|
||||
SettingButton('V2.0.20', 'napcat-update-button', 'secondary'),
|
||||
),
|
||||
]),
|
||||
SettingList([
|
||||
@@ -176,6 +176,16 @@ async function onSettingWindowCreated(view: Element) {
|
||||
),
|
||||
SettingItem('NapCat 文档', '', SettingButton('看看文档', 'open-docs'))
|
||||
]),
|
||||
SettingItem(
|
||||
'Telegram 群',
|
||||
'https://t.me/+nLZEnpne-pQ1OWFl',
|
||||
SettingButton('进去逛逛', 'open-telegram')
|
||||
),
|
||||
SettingItem(
|
||||
'QQ 群',
|
||||
'518662028',
|
||||
SettingButton('我要进去', 'open-qq-group')
|
||||
),
|
||||
'</div>',
|
||||
].join(''),
|
||||
'text/html',
|
||||
@@ -188,6 +198,12 @@ async function onSettingWindowCreated(view: Element) {
|
||||
doc.querySelector('#open-docs')?.addEventListener('click', () => {
|
||||
window.open('https://napneko.github.io/', '_blank');
|
||||
});
|
||||
doc.querySelector('#open-telegram')?.addEventListener('click', () => {
|
||||
window.open('https://t.me/+nLZEnpne-pQ1OWFl', '_blank');
|
||||
});
|
||||
doc.querySelector('#open-qq-group')?.addEventListener('click', () => {
|
||||
window.open('https://qm.qq.com/q/VfjAq5HIMS', '_blank');
|
||||
});
|
||||
// 生成反向地址列表
|
||||
const buildHostListItem = (
|
||||
type: string,
|
||||
|
@@ -164,7 +164,7 @@ async function onSettingWindowCreated(view) {
|
||||
SettingItem(
|
||||
'<span id="napcat-update-title">Napcat</span>',
|
||||
void 0,
|
||||
SettingButton("V2.0.2", "napcat-update-button", "secondary")
|
||||
SettingButton("V2.0.20", "napcat-update-button", "secondary")
|
||||
)
|
||||
]),
|
||||
SettingList([
|
||||
@@ -308,6 +308,16 @@ async function onSettingWindowCreated(view) {
|
||||
),
|
||||
SettingItem("NapCat 文档", "", SettingButton("看看文档", "open-docs"))
|
||||
]),
|
||||
SettingItem(
|
||||
"Telegram 群",
|
||||
"https://t.me/+nLZEnpne-pQ1OWFl",
|
||||
SettingButton("进去逛逛", "open-telegram")
|
||||
),
|
||||
SettingItem(
|
||||
"QQ 群",
|
||||
"518662028",
|
||||
SettingButton("我要进去", "open-qq-group")
|
||||
),
|
||||
"</div>"
|
||||
].join(""),
|
||||
"text/html"
|
||||
@@ -318,6 +328,12 @@ async function onSettingWindowCreated(view) {
|
||||
doc.querySelector("#open-docs")?.addEventListener("click", () => {
|
||||
window.open("https://napneko.github.io/", "_blank");
|
||||
});
|
||||
doc.querySelector("#open-telegram")?.addEventListener("click", () => {
|
||||
window.open("https://t.me/+nLZEnpne-pQ1OWFl", "_blank");
|
||||
});
|
||||
doc.querySelector("#open-qq-group")?.addEventListener("click", () => {
|
||||
window.open("https://qm.qq.com/q/VfjAq5HIMS", "_blank");
|
||||
});
|
||||
const buildHostListItem = (type, host, index, inputAttrs = {}) => {
|
||||
const dom = {
|
||||
container: document.createElement("setting-item"),
|
||||
|
Reference in New Issue
Block a user