Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7380665cc2 | ||
|
|
2c57faf117 | ||
|
|
8b0d186625 | ||
|
|
3ba1bd9565 | ||
|
|
8aec6aec1b | ||
|
|
36ae7bf923 | ||
|
|
4ed4dfd450 | ||
|
|
b15d02535e | ||
|
|
974528fe7e | ||
|
|
d2d0b258bc | ||
|
|
2dcba633ba | ||
|
|
53ceb85801 | ||
|
|
dbba6b3ffe | ||
|
|
03dd89add0 | ||
|
|
7fc70bc5ce | ||
|
|
6758825895 | ||
|
|
ae53d27313 | ||
|
|
86884b6ba2 | ||
|
|
776cc8cefd | ||
|
|
66542eda26 | ||
|
|
34a699c568 | ||
|
|
2a06688479 | ||
|
|
976331af94 | ||
|
|
46b0532f84 | ||
|
|
819f76afbf | ||
|
|
938074c654 | ||
|
|
d16f493136 | ||
|
|
4c8419d5ab | ||
|
|
fbba3d5ade | ||
|
|
cf80c787c3 | ||
|
|
7b58681b2b | ||
|
|
7c2eacf0dc | ||
|
|
e09c3c1146 | ||
|
|
cec011bdfa | ||
|
|
9cbaafe806 | ||
|
|
0ddf21a2f5 | ||
|
|
b9dcedacf5 | ||
|
|
b42b6c3cf0 | ||
|
|
740d2118f1 | ||
|
|
77bdcfd249 | ||
|
|
896e1c209a | ||
|
|
cff07c7ce5 | ||
|
|
5c04b799a6 | ||
|
|
1fc4655ae1 | ||
|
|
eb07cdb715 | ||
|
|
964fd98914 | ||
|
|
f9764c9559 | ||
|
|
b71a4913eb |
No files matched your search
@@ -1,16 +1,6 @@
|
||||
# {VERSION}
|
||||
[使用文档](https://napneko.github.io/)
|
||||
|
||||
## Windows 一键包
|
||||
我们提供了轻量化的一键部署方案
|
||||
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
|
||||
|
||||
你可以下载
|
||||
|
||||
NapCat.Shell.Windows.OneKey.zip (无头)
|
||||
|
||||
启动后可自动化部署一键包,教程参考使用文档安装部分
|
||||
|
||||
## 警告
|
||||
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
|
||||
**默认WebUi密钥为随机密码 控制台查看**
|
||||
|
||||
@@ -84,8 +84,8 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
`| 项目 | 值 |`,
|
||||
`| :--- | :--- |`,
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🕐 开始时间 | ${time} |`,
|
||||
'',
|
||||
@@ -165,8 +165,8 @@ export function generateResultComment (
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
`| 项目 | 值 |`,
|
||||
`| :--- | :--- |`,
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
...(version ? [`| 🏷️ 版本号 | \`${version}\` |`] : []),
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 构建日志 | [查看详情](${runUrl}) |`,
|
||||
@@ -179,7 +179,7 @@ export function generateResultComment (
|
||||
lines.push('', '---', '', '## ⚠️ 错误详情', '');
|
||||
for (const target of failedTargets) {
|
||||
lines.push(
|
||||
`<details>`,
|
||||
'<details>',
|
||||
`<summary>🔴 <b>${target.name}</b> 构建错误</summary>`,
|
||||
'',
|
||||
'```',
|
||||
@@ -228,4 +228,3 @@ export function generateResultComment (
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* publish-release-hash.mjs
|
||||
*
|
||||
* 读取 release.json(不存在则创建),追加新版本的 Shell/Framework napcat.mjs SHA512,
|
||||
* 保留最近 100 条后写回文件。
|
||||
*
|
||||
* 用法:
|
||||
* node .github/scripts/publish-release-hash.mjs \
|
||||
* --version v4.9.0 \
|
||||
* --shell ./artifacts/NapCat.Shell/napcat.mjs \
|
||||
* --framework ./artifacts/NapCat.Framework/napcat.mjs \
|
||||
* --file ./hash-repo/release.json
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
|
||||
// ─── CLI 参数解析 ────────────────────────────────────────────────────────────
|
||||
|
||||
function parseArgs () {
|
||||
const args = process.argv.slice(2);
|
||||
const result = {};
|
||||
for (let i = 0; i < args.length; i += 2) {
|
||||
result[args[i].replace(/^--/, '')] = args[i + 1];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const { version, shell: shellPath, framework: frameworkPath, file: outputFile } = parseArgs();
|
||||
|
||||
if (!version || !shellPath || !frameworkPath || !outputFile) {
|
||||
console.error('Usage: node publish-release-hash.mjs --version <v> --shell <path> --framework <path> --file <path>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// ─── 工具函数 ────────────────────────────────────────────────────────────────
|
||||
|
||||
function sha512File (filePath) {
|
||||
if (!fs.existsSync(filePath)) {
|
||||
throw new Error(`File not found: ${filePath}`);
|
||||
}
|
||||
const buf = fs.readFileSync(filePath);
|
||||
return crypto.createHash('sha512').update(buf).digest('hex');
|
||||
}
|
||||
|
||||
// ─── 主逻辑 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
const MAX_ENTRIES = 100;
|
||||
|
||||
// 1. 计算哈希
|
||||
console.log(`Computing SHA512 for Shell: ${shellPath}`);
|
||||
const shellHash = sha512File(shellPath);
|
||||
console.log(`Computing SHA512 for Framework: ${frameworkPath}`);
|
||||
const frameworkHash = sha512File(frameworkPath);
|
||||
|
||||
// 2. 读取现有 release.json,不存在则创建空数组
|
||||
let entries = [];
|
||||
if (fs.existsSync(outputFile)) {
|
||||
entries = JSON.parse(fs.readFileSync(outputFile, 'utf-8'));
|
||||
console.log(`Loaded existing ${outputFile} with ${entries.length} entries.`);
|
||||
} else {
|
||||
console.log(`${outputFile} not found, will create it.`);
|
||||
}
|
||||
|
||||
// 3. 追加新条目,去除同版本旧条目,滚动保留最近 MAX_ENTRIES 条
|
||||
const newEntry = {
|
||||
version,
|
||||
shell: { sha512: shellHash },
|
||||
framework: { sha512: frameworkHash },
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const updated = [
|
||||
...entries.filter(e => e.version !== version),
|
||||
newEntry,
|
||||
].slice(-MAX_ENTRIES);
|
||||
|
||||
// 4. 写回文件
|
||||
fs.writeFileSync(outputFile, JSON.stringify(updated, null, 2) + '\n', 'utf-8');
|
||||
console.log(`✅ Written ${updated.length} entries to ${outputFile}`);
|
||||
@@ -9,8 +9,8 @@ on:
|
||||
permissions: write-all
|
||||
|
||||
env:
|
||||
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
|
||||
OPENROUTER_MODEL: "deepseek-v3.2-chat"
|
||||
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
|
||||
OPENAI_MODEL: "stepfun/step-3.5-flash:free"
|
||||
RELEASE_NAME: "NapCat"
|
||||
|
||||
jobs:
|
||||
@@ -218,11 +218,11 @@ jobs:
|
||||
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
|
||||
cd ..
|
||||
|
||||
- name: Generate release note via OpenRouter
|
||||
- name: Generate release note
|
||||
env:
|
||||
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
|
||||
OPENROUTER_API_URL: ${{ env.OPENROUTER_API_URL }}
|
||||
OPENROUTER_MODEL: ${{ env.OPENROUTER_MODEL }}
|
||||
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
|
||||
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
|
||||
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
|
||||
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
|
||||
run: |
|
||||
@@ -395,20 +395,19 @@ jobs:
|
||||
BODY=$(jq -n \
|
||||
--arg system "$SYSTEM_PROMPT" \
|
||||
--arg user "$USER_CONTENT" \
|
||||
--arg model "$OPENROUTER_MODEL" \
|
||||
--arg model "$OPENAI_MODEL" \
|
||||
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
|
||||
|
||||
echo "=== OpenRouter request body ==="
|
||||
echo "=== request body ==="
|
||||
echo "$BODY" | jq .
|
||||
|
||||
# 调用 OpenRouter
|
||||
if RESPONSE=$(curl -s -X POST "$OPENROUTER_API_URL" \
|
||||
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
|
||||
-H "Authorization: Bearer $OPENAI_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$BODY"); then
|
||||
echo "=== raw response ==="
|
||||
echo "$RESPONSE"
|
||||
echo "=== OpenRouter raw response ==="
|
||||
echo "=== parsed response ==="
|
||||
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
|
||||
echo "$RESPONSE" | jq .
|
||||
else
|
||||
@@ -419,7 +418,7 @@ jobs:
|
||||
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -z "$RELEASE_BODY" ]; then
|
||||
echo "❌ OpenRouter failed to generate release note, using default.md"
|
||||
echo "❌ LLM failed to generate release note, using default.md"
|
||||
# 替换默认模板中的版本占位符
|
||||
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
|
||||
else
|
||||
@@ -436,18 +435,19 @@ jobs:
|
||||
echo "=== generated release note ==="
|
||||
cat CHANGELOG.md
|
||||
|
||||
- name: Create Release Draft and Upload Artifacts
|
||||
uses: softprops/action-gh-release@v1
|
||||
- name: Create Release and Upload Artifacts
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: NapCat ${{ github.ref_name }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
body_path: CHANGELOG.md
|
||||
files: |
|
||||
NapCat.Shell.Windows.Node.zip
|
||||
NapCat.Framework.zip
|
||||
NapCat.Shell.zip
|
||||
NapCat.Shell.Windows.OneKey.zip
|
||||
draft: true
|
||||
draft: false
|
||||
|
||||
|
||||
- name: Update apifox
|
||||
@@ -478,3 +478,31 @@ jobs:
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-binary @apifox_payload.json
|
||||
|
||||
- name: Publish release hash
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="${GITHUB_REF#refs/tags/}"
|
||||
HASH_REPO="NapNeko/napcat-release-hash"
|
||||
|
||||
gh auth setup-git
|
||||
gh repo clone "$HASH_REPO" hash-repo
|
||||
|
||||
node .github/scripts/publish-release-hash.mjs \
|
||||
--version "$VERSION" \
|
||||
--shell "./artifacts/NapCat.Shell/napcat.mjs" \
|
||||
--framework "./artifacts/NapCat.Framework/napcat.mjs" \
|
||||
--file "./hash-repo/release.json"
|
||||
|
||||
cd hash-repo
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add release.json
|
||||
if git diff --cached --quiet; then
|
||||
echo "No changes to commit"
|
||||
else
|
||||
git commit -m "chore: update release hash for ${VERSION}"
|
||||
git push origin HEAD:main || git push origin HEAD:master
|
||||
fi
|
||||
|
||||
@@ -5,47 +5,52 @@
|
||||
|
||||
_Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
> 云起兮风生,心向远方兮路未曾至.
|
||||
> Where clouds rise and winds are born, the heart yearns for distant lands yet untraveled.
|
||||
|
||||
English | [简体中文](./docs/README_zh-CN.md) | [繁體中文](./docs/README_zh-TW.md) | [日本語](./docs/README_ja.md) | [한국어](./docs/README_ko.md) | [Русский](./docs/README_ru.md) | [العربية](./docs/README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## New Feature
|
||||
## Notice
|
||||
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested.
|
||||
|
||||
在 v4.8.115+ 版本开始
|
||||
### Community Groups
|
||||
|
||||
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
|
||||
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
|
||||
You can get the join password directly from the **About** page of the WebUI.
|
||||
|
||||
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
|
||||
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> Note: The join key is only valid for the latest 100 versions, and requires NapCat version >= 4.17.31. If it fails, please update.
|
||||
|
||||
## Welcome
|
||||
|
||||
- NapCatQQ is a modern implementation of the Bot protocol based on NTQQ.
|
||||
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
|
||||
|
||||
## Feature
|
||||
## Features
|
||||
|
||||
- **Easy to Use**
|
||||
- 作为初学者能够轻松使用.
|
||||
- Beginners can get started effortlessly.
|
||||
- **Quick and Efficient**
|
||||
- 在低内存操作系统长时运行.
|
||||
- Runs for extended periods on low-memory systems.
|
||||
- **Rich API Interface**
|
||||
- 完整实现了大部分标准接口.
|
||||
- Fully implements most standard interfaces.
|
||||
- **Stable and Reliable**
|
||||
- 持续稳定的开发与维护.
|
||||
- Continuous and stable development and maintenance.
|
||||
|
||||
## Quick Start
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
|
||||
Download the latest version from the [Release](https://github.com/NapNeko/NapCatQQ/releases/) page.
|
||||
|
||||
**首次使用**请务必查看如下文档看使用教程
|
||||
**First-time users** should make sure to read the documentation below for a usage guide.
|
||||
|
||||
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
|
||||
> This is a non-profit project. For integration issues, basic questions, or underlying framework issues, please search for solutions on your own — this project's community does not provide such support.
|
||||
|
||||
## Link
|
||||
## Links
|
||||
|
||||
| Docs | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
@@ -53,37 +58,34 @@ _Modern protocol-side framework implemented based on NTQQ._
|
||||
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| QQ Group | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/8zJMLjqy2Y) | [](https://qm.qq.com/q/CMmPbGw0jA) | [](https://qm.qq.com/q/I6LU87a0Yq) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Telegram | [](https://t.me/napcatqq) |
|
||||
|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
|
||||
| QQ Groups | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> Please do not mention this project in other communities (including other protocol-side or related application-side projects) to avoid disputes. If you have suggestions, please discuss them in the official group or submit a PR.
|
||||
|
||||
## Thanks
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — Great support for this project; some code was referenced (with permission)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — An LLM Bot framework that perfectly integrates with this project
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — A cyber companion Bot framework
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — A message export tool based on NapCat
|
||||
|
||||
- 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||
- And most importantly, thank you — the person reading this right now~
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
|
||||
This project is open-sourced under a hybrid license. When using this project, please note the following:
|
||||
|
||||
1. 第三方库代码或修改部分遵循其原始开源许可.
|
||||
2. 本项目获取部分项目授权而不受部分约束
|
||||
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
|
||||
1. Third-party library code or modified portions follow their original open-source licenses.
|
||||
2. This project has obtained authorization from certain projects and is not subject to some restrictions.
|
||||
3. The remaining logic code of the project is governed by the [repository license](./LICENSE).
|
||||
|
||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||
**This repository is solely intended to improve usability and implement message push features. Furthermore, developing any project based on NapCat code without prior authorization from the repository's main author is prohibited. Please comply with local laws and regulations when using this project. Any issues arising from misuse are the responsibility of the user and anyone providing tutorials for unauthorized use.**
|
||||
@@ -0,0 +1,93 @@
|
||||
<div dir="rtl">
|
||||
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=left />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_إطار عمل حديث على جانب البروتوكول مبني على NTQQ._
|
||||
|
||||
> حيث تنهض السحب وتولد الرياح، يتوق القلب إلى أراضٍ بعيدة لم تُسلك بعد.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | العربية
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## إعلان
|
||||
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com.
|
||||
|
||||
### مجموعات المجتمع
|
||||
|
||||
يمكنك الحصول على كلمة مرور الانضمام مباشرةً من **صفحة "حول" في WebUI**:
|
||||
|
||||
- [NapCat Family] Happy Family 1090875633:https://qm.qq.com/q/VwpnklcXqo
|
||||
- [NapCat Family] Royal Relatives 1059714215:https://qm.qq.com/q/gq18RH7o7S
|
||||
- [NapCat Family] Loving Family 1085662710:https://qm.qq.com/q/XyiyGPqa42
|
||||
- [NapCat Family] Joyful Family 1085359803:https://qm.qq.com/q/E4nfkGD6oK
|
||||
|
||||
## مرحباً
|
||||
|
||||
- NapCatQQ هو تطبيق حديث لبروتوكول Bot مبني على NTQQ
|
||||
|
||||
## المميزات
|
||||
|
||||
- **سهل الاستخدام**
|
||||
- يمكن للمبتدئين البدء بسهولة.
|
||||
- **سريع وفعال**
|
||||
- يعمل لفترات طويلة على أنظمة ذات ذاكرة منخفضة.
|
||||
- **واجهة API غنية**
|
||||
- تنفيذ كامل لمعظم الواجهات القياسية.
|
||||
- **مستقر وموثوق**
|
||||
- تطوير وصيانة مستمرة ومستقرة.
|
||||
|
||||
## البداية السريعة
|
||||
|
||||
قم بتنزيل أحدث إصدار من صفحة [Release](https://github.com/NapNeko/NapCatQQ/releases/)
|
||||
|
||||
**للمستخدمين لأول مرة** تأكد من قراءة الوثائق أدناه للحصول على دليل الاستخدام
|
||||
|
||||
> هذا مشروع غير ربحي. للمشاكل المتعلقة بالتكامل والأسئلة الأساسية ومشاكل إطار العمل الأساسي، يرجى البحث عن الحلول بنفسك — مجتمع هذا المشروع لا يقدم مثل هذا الدعم.
|
||||
|
||||
## الروابط
|
||||
|
||||
| الوثائق | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| الوثائق | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| مجموعات QQ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> يرجى عدم ذكر هذا المشروع في مجتمعات أخرى (بما في ذلك مشاريع البروتوكول الأخرى / مشاريع التطبيقات ذات الصلة) لتجنب الخلافات. إذا كانت لديك اقتراحات، يرجى مناقشتها في المجموعة الرسمية أو تقديم PR.
|
||||
|
||||
## شكر وتقدير
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — دعم كبير لهذا المشروع؛ تمت الإشارة إلى بعض الأكواد (بإذن)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — إطار عمل LLM Bot متوافق تماماً مع هذا المشروع
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — إطار عمل Bot رفيق سيبراني
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — أداة تصدير الرسائل مبنية على NapCat
|
||||
|
||||
- والأهم من ذلك كله، شكراً لك — أنت الذي تقرأ هذا الآن~
|
||||
|
||||
---
|
||||
|
||||
## الرخصة
|
||||
|
||||
هذا المشروع مفتوح المصدر بموجب رخصة هجينة. عند استخدام هذا المشروع، يرجى ملاحظة ما يلي:
|
||||
|
||||
1. كود المكتبات الخارجية أو الأجزاء المعدلة تخضع لرخصها مفتوحة المصدر الأصلية.
|
||||
2. حصل هذا المشروع على إذن من بعض المشاريع ولا يخضع لبعض القيود.
|
||||
3. باقي الكود المنطقي للمشروع يخضع [لرخصة هذا المستودع](../LICENSE).
|
||||
|
||||
**هذا المستودع مخصص فقط لتحسين سهولة الاستخدام وتنفيذ ميزات دفع الرسائل. علاوة على ذلك، يُحظر تطوير أي مشروع بناءً على كود NapCat دون إذن مسبق من المؤلف الرئيسي للمستودع. يرجى الامتثال للقوانين واللوائح المحلية عند الاستخدام. أي مشاكل ناتجة عن سوء الاستخدام تقع على عاتق المستخدم ومن يقدم تعليمات الاستخدام غير المصرح به.**
|
||||
|
||||
</div>
|
||||
@@ -0,0 +1,91 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_NTQQをベースにした最新のプロトコル側フレームワーク._
|
||||
|
||||
> 雲起きて風生じ、心は遠方を向けど路は未だ至らず.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | 日本語 | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## お知らせ
|
||||
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。
|
||||
|
||||
### コミュニティグループ
|
||||
|
||||
**WebUI の「について」ページ** から参加パスワードを直接取得できます:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> 注意:入会キーは最新の100バージョンにのみ有効で、NapCatバージョン >= 4.17.31 が必要です。エラーが発生した場合は更新してください。
|
||||
|
||||
## ようこそ
|
||||
|
||||
- NapCatQQ は NTQQ をベースにした最新の Bot プロトコル側実装です
|
||||
|
||||
## 特徴
|
||||
|
||||
- **簡単に使える**
|
||||
- 初心者でも簡単に使用できます.
|
||||
- **高速で効率的**
|
||||
- 低メモリ環境のOSで長時間稼働できます.
|
||||
- **豊富な API インターフェース**
|
||||
- ほとんどの標準インターフェースを完全に実装しています.
|
||||
- **安定して信頼できる**
|
||||
- 継続的で安定した開発とメンテナンスを行っています.
|
||||
|
||||
## クイックスタート
|
||||
|
||||
最新バージョンは [Release](https://github.com/NapNeko/NapCatQQ/releases/) ページからダウンロードできます
|
||||
|
||||
**初めてご使用の方**は、以下のドキュメントで使用ガイドを必ずご確認ください
|
||||
|
||||
> このプロジェクトは非営利です。連携に関する問題/基本的な問題/下位フレームワークの問題については、ご自身で検索して解決してください。本プロジェクトのコミュニティではそのような回答は提供していません。
|
||||
|
||||
## リンク
|
||||
|
||||
| ドキュメント | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| ドキュメント | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ グループ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 他のコミュニティでこのプロジェクト(他のプロトコル側/関連アプリケーション側のプロジェクトを含む)に言及して論争を引き起こさないでください。提案がある場合は、公式交流グループで議論するか、PRを提出してください。
|
||||
|
||||
## 謝辞
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 本プロジェクトへの多大なサポート、一部コードを参考にしています(許可済み)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 本プロジェクトに完璧に対応した LLM Bot フレームワークです
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) サイバー仲間の 麦麦 Bot フレームワークです
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) NapCat ベースのメッセージエクスポートツールです
|
||||
|
||||
- そして何より大切なのは、画面の前のあなたに感謝することです~
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
本プロジェクトはハイブリッドライセンスの下でオープンソース化されています。本プロジェクトを使用する際は、以下の点にご注意ください:
|
||||
|
||||
1. サードパーティライブラリのコードまたは修正部分は、元のオープンソースライセンスに従います.
|
||||
2. 本プロジェクトは一部のプロジェクトから許可を得ており、一部の制約を受けません.
|
||||
3. プロジェクトのその他のロジックコードは[本リポジトリのオープンソースライセンス](../LICENSE)に従います.
|
||||
|
||||
**本リポジトリは使いやすさの향上とメッセージプッシュ機能の実装のみを目的としています。また、リポジトリの主要作者の事前許可なく NapCat のコードに基づいてプロジェクトを開発することは禁止されています。使用する際は現地の法律と規制を遵守してください。これに起因する問題は、使用者および違反使用チュートリアルの提供者の責任となります。**
|
||||
@@ -0,0 +1,89 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_NTQQ 기반으로 구현된 최신 프로토콜 사이드 프레임워크._
|
||||
|
||||
> 구름이 일고 바람이 불어, 마음은 먼 곳을 향하나 길은 아직 닿지 못했네.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | 한국어 | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 공지
|
||||
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요.
|
||||
### 커뮤니티 그룹
|
||||
|
||||
**WebUI 의 「정보」페이지** 에서 입장 비밀번호를 바로 확인할 수 있습니다:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> 참고: 가입 키는 최신 100개 버전에서만 유효하며, NapCat 버전 >= 4.17.31이 필요합니다. 오류가 발생하면 업데이트하세요.
|
||||
## 환영합니다
|
||||
|
||||
- NapCatQQ는 NTQQ를 기반으로 한 최신 Bot 프로토콜 구현체입니다
|
||||
|
||||
## 특징
|
||||
|
||||
- **사용하기 쉬움**
|
||||
- 초보자도 쉽게 사용할 수 있습니다.
|
||||
- **빠르고 효율적**
|
||||
- 저메모리 시스템에서도 장시간 안정적으로 실행됩니다.
|
||||
- **풍부한 API 인터페이스**
|
||||
- 대부분의 표준 인터페이스를 완전히 구현했습니다.
|
||||
- **안정적이고 신뢰할 수 있음**
|
||||
- 지속적이고 안정적인 개발과 유지보수를 하고 있습니다.
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
[Release](https://github.com/NapNeko/NapCatQQ/releases/) 페이지에서 최신 버전을 다운로드할 수 있습니다
|
||||
|
||||
**처음 사용하시는 분**은 아래 문서에서 사용 가이드를 반드시 확인해 주세요
|
||||
|
||||
> 이 프로젝트는 비영리입니다. 연동 문제/기본 문제/하위 프레임워크 문제는 직접 검색하여 해결해 주세요. 본 프로젝트 커뮤니티에서는 이러한 지원을 제공하지 않습니다.
|
||||
|
||||
## 링크
|
||||
|
||||
| 문서 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 문서 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 그룹 | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 다른 커뮤니티에서 이 프로젝트(다른 프로토콜 측/관련 애플리케이션 측 프로젝트 포함)를 언급하여 논쟁을 일으키지 마세요. 제안이 있으시면 공식 그룹에서 토론하거나 PR을 제출해 주세요.
|
||||
|
||||
## 감사의 말
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — 본 프로젝트에 대한 큰 지원, 일부 코드 참고 (허가 완료)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — 본 프로젝트와 완벽하게 호환되는 LLM Bot 프레임워크
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — 사이버 친구 麦麦 Bot 프레임워크
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — NapCat 기반의 메시지 내보내기 도구
|
||||
|
||||
- 그리고 가장 중요한 것은, 지금 이 글을 읽고 있는 당신에게 감사드립니다~
|
||||
|
||||
---
|
||||
|
||||
## 라이선스
|
||||
|
||||
이 프로젝트는 하이브리드 라이선스로 오픈소스화되어 있습니다. 이 프로젝트를 사용할 때 다음 사항에 유의해 주세요:
|
||||
|
||||
1. 서드파티 라이브러리 코드 또는 수정된 부분은 원래의 오픈소스 라이선스를 따릅니다.
|
||||
2. 이 프로젝트는 일부 프로젝트로부터 허가를 받아 일부 제한을 받지 않습니다.
|
||||
3. 프로젝트의 나머지 로직 코드는 [본 리포지토리 라이선스](../LICENSE)를 따릅니다.
|
||||
|
||||
**이 리포지토리는 사용 편의성 향상과 메시지 푸시 기능 구현만을 목적으로 합니다. 또한, 리포지토리 주요 작성자의 사전 승인 없이 NapCat 코드를 기반으로 프로젝트를 개발하는 것은 금지되어 있습니다. 사용 시 현지 법률 및 규정을 준수해 주세요. 이로 인해 발생하는 문제는 사용자 및 위반 사용 튜토리얼 제공자의 책임입니다.**
|
||||
@@ -0,0 +1,91 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_Современный фреймворк на стороне протокола, реализованный на базе NTQQ._
|
||||
|
||||
> Облака поднимаются, ветер рождается, сердце стремится вдаль, но путь ещё не пройден.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | Русский | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Объявление
|
||||
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com.
|
||||
|
||||
### Группы сообщества
|
||||
|
||||
Пароль для вступления можно получить прямо на **странице «О программе» в WebUI**:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> Примечание: Ключ для входа действителен только для последних 100 версий и требует версию NapCat >= 4.17.31. Если возникает ошибка, пожалуйста, обновитесь.
|
||||
|
||||
## Добро пожаловать
|
||||
|
||||
- NapCatQQ — это современная реализация протокола Bot на базе NTQQ
|
||||
|
||||
## Особенности
|
||||
|
||||
- **Простота использования**
|
||||
- Начинающие пользователи смогут легко освоить работу.
|
||||
- **Скорость и эффективность**
|
||||
- Длительная работа на системах с ограниченным объёмом памяти.
|
||||
- **Богатый API-интерфейс**
|
||||
- Полная реализация большинства стандартных интерфейсов.
|
||||
- **Стабильность и надёжность**
|
||||
- Постоянная стабильная разработка и поддержка.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
Скачайте последнюю версию на странице [Release](https://github.com/NapNeko/NapCatQQ/releases/)
|
||||
|
||||
**При первом использовании** обязательно ознакомьтесь с руководством в документации ниже
|
||||
|
||||
> Проект является некоммерческим. Вопросы интеграции, базовые вопросы и вопросы по нижележащему фреймворку решайте самостоятельно — сообщество данного проекта не предоставляет такой поддержки.
|
||||
|
||||
## Ссылки
|
||||
|
||||
| Документация | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Документация | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ группы | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> Пожалуйста, не упоминайте данный проект (включая другие протокольные/прикладные проекты) в других сообществах во избежание споров. Если у вас есть предложения, обсуждайте их в официальной группе или отправляйте PR.
|
||||
|
||||
## Благодарности
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — большая поддержка данного проекта, частично использован код (с разрешения)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — фреймворк LLM Bot, идеально совместимый с данным проектом
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — кибер-друг 麦麦, Bot-фреймворк
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — инструмент экспорта сообщений на базе NapCat
|
||||
|
||||
- И самое главное — спасибо вам, читающему это~
|
||||
|
||||
---
|
||||
|
||||
## Лицензия
|
||||
|
||||
Данный проект распространяется с открытым исходным кодом под гибридной лицензией. При использовании данного проекта обратите внимание на следующее:
|
||||
|
||||
1. Код сторонних библиотек или модифицированные части подчиняются их исходным лицензиям с открытым исходным кодом.
|
||||
2. Данный проект получил разрешение от ряда проектов и не подчиняется некоторым ограничениям.
|
||||
3. Остальной логический код проекта распространяется по [лицензии данного репозитория](../LICENSE).
|
||||
|
||||
**Данный репозиторий предназначен исключительно для повышения удобства использования и реализации функций отправки сообщений. Кроме того, запрещается разработка проектов на основе кода NapCat без предварительного разрешения главного автора репозитория. При использовании соблюдайте местное законодательство. За любые проблемы, вызванные нарушением, несут ответственность пользователь и лицо, предоставившее инструкции по незаконному использованию.**
|
||||
@@ -0,0 +1,91 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_基于 NTQQ 实现的现代化协议端框架._
|
||||
|
||||
> 云起兮风生,心向远方兮路未曾至.
|
||||
|
||||
[English](../README.md) | 简体中文 | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 公告
|
||||
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com 。
|
||||
|
||||
### 交流群
|
||||
|
||||
可直接在 **WebUI 关于页面** 获取入群密码:
|
||||
|
||||
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群号(1090875633)
|
||||
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群号(1059714215)
|
||||
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群号(1085662710)
|
||||
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群号(1085359803)
|
||||
|
||||
> 注意:入群密钥只适合最新的100个版本,且 NapCat 版本需 >= 4.17.31,如果不符合请更新。
|
||||
|
||||
## 欢迎
|
||||
|
||||
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
|
||||
|
||||
## 特性
|
||||
|
||||
- **易于使用**
|
||||
- 作为初学者能够轻松使用.
|
||||
- **快速高效**
|
||||
- 在低内存操作系统长时运行.
|
||||
- **丰富的 API 接口**
|
||||
- 完整实现了大部分标准接口.
|
||||
- **稳定可靠**
|
||||
- 持续稳定的开发与维护.
|
||||
|
||||
## 快速开始
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
|
||||
|
||||
**首次使用**请务必查看如下文档看使用教程
|
||||
|
||||
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
|
||||
|
||||
## 链接
|
||||
|
||||
| 文档 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 文档 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 群 | [欢乐一家亲](https://qm.qq.com/q/VwpnklcXqo) | [皇亲国戚](https://qm.qq.com/q/gq18RH7o7S) | [相亲相爱一家人](https://qm.qq.com/q/XyiyGPqa42) | [开心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
|
||||
|
||||
## 致谢
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
|
||||
|
||||
- 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||
|
||||
---
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
|
||||
|
||||
1. 第三方库代码或修改部分遵循其原始开源许可.
|
||||
2. 本项目获取部分项目授权而不受部分约束
|
||||
2. 项目其余逻辑代码采用[本仓库开源许可](../LICENSE).
|
||||
|
||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||
@@ -0,0 +1,91 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_基於 NTQQ 實現的現代化協議端框架._
|
||||
|
||||
> 雲起兮風生,心向遠方兮路未曾至.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | 繁體中文 | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 公告
|
||||
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。
|
||||
|
||||
### 交流群
|
||||
|
||||
可直接在 **WebUI 關於頁面** 取得入群密碼:
|
||||
|
||||
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群號(1090875633)
|
||||
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群號(1059714215)
|
||||
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群號(1085662710)
|
||||
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群號(1085359803)
|
||||
|
||||
> 注意:入群密鑰只適用於最新的100個版本,且 NapCat 版本需 >= 4.17.31,如果錯誤請更新。
|
||||
|
||||
## 歡迎
|
||||
|
||||
- NapCatQQ 是現代化的基於 NTQQ 的 Bot 協議端實現
|
||||
|
||||
## 特性
|
||||
|
||||
- **易於使用**
|
||||
- 初學者也能輕鬆上手.
|
||||
- **快速高效**
|
||||
- 在低記憶體系統長時間穩定運行.
|
||||
- **豐富的 API 介面**
|
||||
- 完整實現了大部分標準介面.
|
||||
- **穩定可靠**
|
||||
- 持續穩定的開發與維護.
|
||||
|
||||
## 快速開始
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 頁面下載最新版本
|
||||
|
||||
**首次使用**請務必查看以下文件中的使用教學
|
||||
|
||||
> 專案為非營利性質,涉及 對接問題/基礎問題/底層框架問題 請自行搜尋解決,本專案社群不提供此類解答。
|
||||
|
||||
## 連結
|
||||
|
||||
| 文件 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 文件 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 群 | [歡樂一家親](https://qm.qq.com/q/VwpnklcXqo) | [皇親國戚](https://qm.qq.com/q/gq18RH7o7S) | [相親相愛一家人](https://qm.qq.com/q/XyiyGPqa42) | [開心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 請不要在其他社群提及本專案(包括其他協議端/相關應用端專案)以免引發爭論。如有建議,請到官方交流群討論或提交 PR。
|
||||
|
||||
## 致謝
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 對本專案的大力支持,參考部分程式碼(已獲授權)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美適配本專案的 LLM Bot 框架,在此推薦
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一隻賽博群友 麥麥 Bot 框架,在此推薦
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基於 NapCat 的訊息匯出工具,在此推薦
|
||||
|
||||
- 不過最最重要的,還是要感謝螢幕前的你哦~
|
||||
|
||||
---
|
||||
|
||||
## 授權條款
|
||||
|
||||
本專案採用混合協議開源,因此使用本專案時,您需要注意以下幾點:
|
||||
|
||||
1. 第三方函式庫程式碼或修改部分遵循其原始開源授權.
|
||||
2. 本專案已獲取部分專案授權而不受部分約束.
|
||||
3. 專案其餘邏輯程式碼採用[本倉庫開源授權](../LICENSE).
|
||||
|
||||
**本倉庫僅用於提高易用性,實現訊息推送類功能,此外,禁止任何專案未經倉庫主作者授權基於 NapCat 程式碼開發。使用請遵守當地法律法規,由此造成的問題由使用者和提供違規使用教學者負責。**
|
||||
@@ -16,7 +16,6 @@
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"ajv": "^8.13.0",
|
||||
"file-type": "^21.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -151,7 +151,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
const isTargetHttps = targetUrl.protocol === 'https:';
|
||||
const proxyPort = parseInt(proxyUrl.port) || (proxyUrl.protocol === 'https:' ? 443 : 80);
|
||||
|
||||
|
||||
// 代理认证头
|
||||
const proxyAuthHeader = proxyUrl.username && proxyUrl.password
|
||||
? { 'Proxy-Authorization': 'Basic ' + Buffer.from(`${decodeURIComponent(proxyUrl.username)}:${decodeURIComponent(proxyUrl.password)}`).toString('base64') }
|
||||
@@ -165,7 +165,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
method: 'CONNECT',
|
||||
path: `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
headers: {
|
||||
'Host': `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
Host: `${targetUrl.hostname}:${targetUrl.port || 443}`,
|
||||
...proxyAuthHeader,
|
||||
},
|
||||
});
|
||||
@@ -179,7 +179,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
// 在隧道上建立 TLS 连接
|
||||
const tlsSocket = tls.connect({
|
||||
socket: socket,
|
||||
socket,
|
||||
servername: targetUrl.hostname,
|
||||
rejectUnauthorized: true,
|
||||
}, () => {
|
||||
@@ -187,14 +187,14 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
const requestPath = targetUrl.pathname + targetUrl.search;
|
||||
const requestHeaders = {
|
||||
...headers,
|
||||
'Host': targetUrl.hostname,
|
||||
'Connection': 'close',
|
||||
Host: targetUrl.hostname,
|
||||
Connection: 'close',
|
||||
};
|
||||
|
||||
|
||||
const headerLines = Object.entries(requestHeaders)
|
||||
.map(([key, value]) => `${key}: ${value}`)
|
||||
.join('\r\n');
|
||||
|
||||
|
||||
const httpRequest = `GET ${requestPath} HTTP/1.1\r\n${headerLines}\r\n\r\n`;
|
||||
tlsSocket.write(httpRequest);
|
||||
});
|
||||
@@ -209,19 +209,19 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
|
||||
tlsSocket.on('data', (chunk: Buffer) => {
|
||||
responseData = Buffer.concat([responseData, chunk]);
|
||||
|
||||
|
||||
if (!headersParsed) {
|
||||
const headerEndIndex = responseData.indexOf('\r\n\r\n');
|
||||
if (headerEndIndex !== -1) {
|
||||
headersParsed = true;
|
||||
const headerStr = responseData.subarray(0, headerEndIndex).toString();
|
||||
const headerLines = headerStr.split('\r\n');
|
||||
|
||||
|
||||
// 解析状态码
|
||||
const statusLine = headerLines[0];
|
||||
const statusMatch = statusLine?.match(/HTTP\/\d\.\d\s+(\d+)/);
|
||||
statusCode = statusMatch ? parseInt(statusMatch[1]!) : 0;
|
||||
|
||||
|
||||
// 解析响应头
|
||||
for (const line of headerLines.slice(1)) {
|
||||
const [key, ...valueParts] = line.split(':');
|
||||
@@ -232,7 +232,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
redirectLocation = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bodyData = responseData.subarray(headerEndIndex + 4);
|
||||
}
|
||||
} else {
|
||||
@@ -243,18 +243,18 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
tlsSocket.on('end', () => {
|
||||
// 处理重定向
|
||||
if (statusCode >= 300 && statusCode < 400 && redirectLocation) {
|
||||
const redirectUrl = redirectLocation.startsWith('http')
|
||||
? redirectLocation
|
||||
const redirectUrl = redirectLocation.startsWith('http')
|
||||
? redirectLocation
|
||||
: `${targetUrl.protocol}//${targetUrl.host}${redirectLocation}`;
|
||||
httpDownloadWithProxy(redirectUrl, headers, proxy).then(resolve).catch(reject);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (statusCode !== 200) {
|
||||
reject(new Error(`下载失败: ${statusCode}`));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 处理 chunked 编码
|
||||
if (isChunked) {
|
||||
resolve(parseChunkedBody(bodyData));
|
||||
@@ -282,7 +282,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
path: url, // 完整 URL
|
||||
headers: {
|
||||
...headers,
|
||||
'Host': targetUrl.hostname,
|
||||
Host: targetUrl.hostname,
|
||||
...proxyAuthHeader,
|
||||
},
|
||||
}, (response) => {
|
||||
@@ -304,26 +304,26 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
|
||||
function parseChunkedBody (data: Buffer): Buffer {
|
||||
const chunks: Buffer[] = [];
|
||||
let offset = 0;
|
||||
|
||||
|
||||
while (offset < data.length) {
|
||||
// 查找 chunk 大小行的结束
|
||||
const lineEnd = data.indexOf('\r\n', offset);
|
||||
if (lineEnd === -1) break;
|
||||
|
||||
|
||||
const sizeStr = data.subarray(offset, lineEnd).toString().split(';')[0]; // 忽略 chunk 扩展
|
||||
const chunkSize = parseInt(sizeStr!, 16);
|
||||
|
||||
|
||||
if (chunkSize === 0) break; // 最后一个 chunk
|
||||
|
||||
|
||||
const chunkStart = lineEnd + 2;
|
||||
const chunkEnd = chunkStart + chunkSize;
|
||||
|
||||
|
||||
if (chunkEnd > data.length) break;
|
||||
|
||||
|
||||
chunks.push(data.subarray(chunkStart, chunkEnd));
|
||||
offset = chunkEnd + 2; // 跳过 chunk 数据后的 \r\n
|
||||
}
|
||||
|
||||
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
|
||||
@@ -253,7 +253,6 @@ export async function getAllTags (mirror?: string): Promise<{ tags: string[], mi
|
||||
return getAllTagsFromMirror('NapNeko', 'NapCatQQ', mirror);
|
||||
}
|
||||
|
||||
|
||||
export async function getLatestTag (mirror?: string): Promise<string> {
|
||||
const { tags } = await getAllTags(mirror);
|
||||
|
||||
|
||||
@@ -21,4 +21,4 @@ export interface ILogWrapper {
|
||||
logWarn (...args: any[]): void;
|
||||
logFatal (...args: any[]): void;
|
||||
logMessage (msg: unknown, selfInfo: unknown): void;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* GitHub 镜像配置模块
|
||||
* 提供统一的镜像源管理,支持复杂网络环境
|
||||
*
|
||||
*
|
||||
* 镜像源测试时间: 2026-01-03
|
||||
* 测试通过: 55/61 完全可用
|
||||
*/
|
||||
@@ -17,7 +17,7 @@ import { PromiseTimer } from './helper';
|
||||
* GitHub 文件加速镜像
|
||||
* 用于加速 release assets 下载
|
||||
* 按延迟排序,优先使用快速镜像
|
||||
*
|
||||
*
|
||||
* 测试时间: 2026-01-03
|
||||
* 镜像支持 301/302 重定向
|
||||
* 懒加载测速:首次使用时自动测速,缓存 30 分钟
|
||||
@@ -74,7 +74,7 @@ export const GITHUB_FILE_MIRRORS = [
|
||||
* GitHub API 镜像
|
||||
* 用于访问 GitHub API(作为备选方案)
|
||||
* 注:优先使用非 API 方法,减少对 API 的依赖
|
||||
*
|
||||
*
|
||||
* 经测试,大部分代理镜像不支持 API 转发
|
||||
* 建议使用 getLatestReleaseTag 等方法避免 API 调用
|
||||
*/
|
||||
@@ -271,8 +271,6 @@ async function performMirrorTest (): Promise<string[]> {
|
||||
.sort((a, b) => a.latency - b.latency)
|
||||
.map(r => r.mirror);
|
||||
|
||||
|
||||
|
||||
// 至少返回原始 URL
|
||||
if (successfulMirrors.length === 0) {
|
||||
return [''];
|
||||
@@ -287,7 +285,6 @@ async function performMirrorTest (): Promise<string[]> {
|
||||
export function clearMirrorCache (): void {
|
||||
cachedFastMirrors = null;
|
||||
cacheTimestamp = 0;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -664,7 +661,7 @@ export function buildReleaseDownloadUrl (
|
||||
|
||||
/**
|
||||
* 获取 GitHub release 信息(优先使用非 API 方法)
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 先通过 git refs 获取 tags
|
||||
* 2. 直接构建下载 URL,不依赖 API
|
||||
@@ -725,7 +722,7 @@ export async function getGitHubRelease (
|
||||
const response = await PromiseTimer(
|
||||
RequestUtil.HttpGetJson<any>(url, 'GET', undefined, {
|
||||
'User-Agent': 'NapCat',
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
Accept: 'application/vnd.github.v3+json',
|
||||
}),
|
||||
currentConfig.timeout
|
||||
);
|
||||
@@ -958,7 +955,7 @@ async function getWorkflowRunsFromHtml (
|
||||
allRuns.push({
|
||||
id,
|
||||
created_at: timeMatch[1],
|
||||
title: title.trim()
|
||||
title: title.trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -994,7 +991,7 @@ async function getWorkflowRunsFromHtml (
|
||||
/**
|
||||
* 通过 API 获取最新的 workflow runs,然后直接拼接 nightly.link 下载链接
|
||||
* 无需解析 HTML,直接使用固定的 URL 格式
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 优先使用 GitHub API
|
||||
* 2. API 失败时,从 GitHub Actions HTML 页面解析
|
||||
@@ -1042,7 +1039,6 @@ async function getArtifactsFromNightlyLink (
|
||||
}
|
||||
}
|
||||
return { artifacts, mirror: runsMirror };
|
||||
|
||||
} catch {
|
||||
return { artifacts: [], mirror: '' };
|
||||
}
|
||||
@@ -1051,7 +1047,7 @@ async function getArtifactsFromNightlyLink (
|
||||
/**
|
||||
* 获取 GitHub Action 最新运行的 artifacts
|
||||
* 用于下载 nightly/dev 版本
|
||||
*
|
||||
*
|
||||
* 策略:
|
||||
* 1. 检查缓存(10分钟有效)
|
||||
* 2. 优先尝试从 nightly.link 获取(无需认证,更稳定)
|
||||
|
||||
@@ -3,4 +3,4 @@ export interface ISubscription {
|
||||
subscribe (listener: LogListener): void;
|
||||
unsubscribe (listener: LogListener): void;
|
||||
notify (msg: string): void;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import path from 'node:path';
|
||||
import { InstanceContext, NapCatCore } from '@/napcat-core/index';
|
||||
import {
|
||||
checkSqliteAvailable,
|
||||
DatabaseHandle,
|
||||
openDatabase,
|
||||
decryptAndOpen,
|
||||
readSingleDatabase,
|
||||
scanAllDatabases,
|
||||
formatScanResults,
|
||||
decryptDatabaseFile,
|
||||
type DatabaseScanResult,
|
||||
type DatabaseReadOptions,
|
||||
type TableInfo,
|
||||
} from 'napcat-database';
|
||||
|
||||
type SQLInputValue = import('node:sqlite').SQLInputValue;
|
||||
|
||||
export class NTQQDatabaseApi {
|
||||
context: InstanceContext;
|
||||
core: NapCatCore;
|
||||
|
||||
constructor (context: InstanceContext, core: NapCatCore) {
|
||||
this.context = context;
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
/** node:sqlite 是否可用 */
|
||||
async isSqliteAvailable (): Promise<boolean> {
|
||||
return checkSqliteAvailable();
|
||||
}
|
||||
|
||||
/** 获取当前账号的 nt_db 目录 */
|
||||
getNtDbDir (): string {
|
||||
return path.resolve(this.core.dataPath, this.core.selfInfo.uin, 'nt_qq', 'nt_db');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取解密缓存目录
|
||||
* 默认: <NapCatDataPath>/db_<uin>/
|
||||
* 可通过 customDir 完全自定义
|
||||
*/
|
||||
getDefaultCacheDir (customDir?: string): string {
|
||||
if (customDir) return customDir;
|
||||
return path.resolve(this.core.NapCatDataPath, `db_${this.core.selfInfo.uin}`);
|
||||
}
|
||||
|
||||
/** 当前是否已获取到数据库 passphrase */
|
||||
hasPassphrase (): boolean {
|
||||
return !!this.core.dbPassphrase;
|
||||
}
|
||||
|
||||
/** 获取 passphrase Buffer,未获取时返回 null */
|
||||
getPassphraseBuffer (): Buffer | null {
|
||||
return this.core.dbPassphrase ? Buffer.from(this.core.dbPassphrase) : null;
|
||||
}
|
||||
|
||||
// ======================== SQLite 数据库操作 ========================
|
||||
|
||||
/**
|
||||
* 打开一个已解密的 SQLite 数据库文件
|
||||
* @param filePath 解密后 .db 文件路径
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
|
||||
*/
|
||||
openDecryptedDb (filePath: string, readOnly = true): DatabaseHandle {
|
||||
return openDatabase(filePath, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并打开一个 NTQQ 加密数据库
|
||||
* @param dbName 数据库文件名 (如 'nt_msg.db') 或完整路径
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @returns DatabaseHandle 实例,使用完毕后需调用 .close()
|
||||
*/
|
||||
openDatabase (dbName: string, readOnly = true, cacheDir?: string): DatabaseHandle | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
|
||||
return decryptAndOpen(dbPath, passphrase, resolvedCacheDir, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行查询并自动关闭连接
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 查询语句
|
||||
* @param params 绑定参数
|
||||
* @returns 查询结果行数组,passphrase 不可用时返回 null
|
||||
*/
|
||||
query<T = Record<string, unknown>> (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): T[] | null {
|
||||
const db = this.openDatabase(dbName);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.query<T>(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行查询,仅返回第一行
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 查询语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
queryOne<T = Record<string, unknown>> (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): T | undefined | null {
|
||||
const db = this.openDatabase(dbName);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.queryOne<T>(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 对加密数据库执行非查询 SQL (INSERT/UPDATE/DELETE 等) 并自动关闭
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
execute (
|
||||
dbName: string,
|
||||
sql: string,
|
||||
params?: SQLInputValue[] | Record<string, SQLInputValue>
|
||||
): { changes: number | bigint; lastInsertRowid: number | bigint; } | null {
|
||||
const db = this.openDatabase(dbName, false);
|
||||
if (!db) return null;
|
||||
try {
|
||||
return db.execute(sql, params);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
// ======================== 批量扫描 ========================
|
||||
|
||||
/**
|
||||
* 读取单个加密数据库的表信息
|
||||
* @param dbName 数据库文件名 (如 'nt_msg.db'),或完整路径
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @param options 其他选项
|
||||
*/
|
||||
readDatabase (dbName: string, cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
|
||||
return readSingleDatabase(dbPath, passphrase, { cacheDir: resolvedCacheDir, ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描所有加密数据库
|
||||
* @param cacheDir 自定义缓存目录,默认 db_<uin>
|
||||
* @param options 其他选项
|
||||
*/
|
||||
scanDatabases (cacheDir?: string, options?: Omit<DatabaseReadOptions, 'cacheDir'>): DatabaseScanResult[] {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return [];
|
||||
|
||||
const resolvedCacheDir = this.getDefaultCacheDir(cacheDir);
|
||||
return scanAllDatabases(this.getNtDbDir(), passphrase, { cacheDir: resolvedCacheDir, ...options });
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅解密数据库文件(不读取表信息,不需要 node:sqlite)
|
||||
* @param dbName 数据库文件名或完整路径
|
||||
* @param outputPath 输出路径,默认保存到 db_<uin>/<dbName>
|
||||
*/
|
||||
decryptDatabase (dbName: string, outputPath?: string): string | null {
|
||||
const passphrase = this.getPassphraseBuffer();
|
||||
if (!passphrase) return null;
|
||||
|
||||
const dbPath = path.isAbsolute(dbName) ? dbName : path.resolve(this.getNtDbDir(), dbName);
|
||||
const outPath = outputPath ?? path.resolve(this.getDefaultCacheDir(), path.basename(dbName));
|
||||
|
||||
return decryptDatabaseFile(dbPath, passphrase, outPath);
|
||||
}
|
||||
|
||||
/** 格式化扫描结果为可读字符串 */
|
||||
formatResults (results: DatabaseScanResult[]): string {
|
||||
return formatScanResults(results);
|
||||
}
|
||||
}
|
||||
|
||||
export { DatabaseHandle };
|
||||
export type { DatabaseScanResult, DatabaseReadOptions, TableInfo };
|
||||
@@ -33,7 +33,7 @@ export class NTQQFileApi {
|
||||
'http://ss.xingzhige.com/music_card/rkey',
|
||||
'https://secret-service.bietiaop.com/rkeys',
|
||||
],
|
||||
this.context.logger
|
||||
this.context.logger
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,3 +9,4 @@ export * from './packet';
|
||||
export * from './file';
|
||||
export * from './online';
|
||||
export * from './flash';
|
||||
export * from './database';
|
||||
@@ -114,7 +114,7 @@ export class NTQQOnlineApi {
|
||||
fileElement: {
|
||||
fileName: actualFolderName,
|
||||
filePath: folderPath,
|
||||
fileSize: "",
|
||||
fileSize: '',
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ export class NTQQPacketApi {
|
||||
this.pkt = new PacketClientSession(this.core);
|
||||
await this.pkt.init(process.pid, table.recv, table.send);
|
||||
try {
|
||||
await this.pkt.operation.FetchRkey(1500);
|
||||
await this.pkt.operation.FetchRkey(3000);
|
||||
} catch (error) {
|
||||
this.logger.logError('测试Packet状态异常', error);
|
||||
return false;
|
||||
|
||||
@@ -164,8 +164,6 @@ export class NTQQWebApi {
|
||||
imgWidth: number = 540,
|
||||
imgHeight: number = 300
|
||||
) {
|
||||
|
||||
|
||||
const cookieObject = await this.core.apis.UserApi.getCookies('qun.qq.com');
|
||||
|
||||
try {
|
||||
@@ -330,10 +328,10 @@ export class NTQQWebApi {
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
async getAlbumListByNTQQ (gc: string) {
|
||||
async getAlbumListByNTQQ (gc: string, attach_info: string = '') {
|
||||
return await this.context.session.getAlbumService().getAlbumList({
|
||||
qun_id: gc,
|
||||
attach_info: '',
|
||||
attach_info,
|
||||
seq: 3331,
|
||||
request_time_line: {
|
||||
request_invoke_time: '0',
|
||||
@@ -477,10 +475,10 @@ export class NTQQWebApi {
|
||||
const client_key = Date.now() * 1000;
|
||||
return await this.context.session.getAlbumService().doQunComment(
|
||||
random_seq, {
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
},
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
},
|
||||
qunId,
|
||||
2,
|
||||
createAlbumMediaFeed(uin, albumId, lloc),
|
||||
@@ -511,13 +509,13 @@ export class NTQQWebApi {
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
return await this.context.session.getAlbumService().doQunLike(
|
||||
random_seq, {
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
}, {
|
||||
id,
|
||||
status: 1,
|
||||
},
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
}, {
|
||||
id,
|
||||
status: 1,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, lloc)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -212,7 +212,7 @@ export enum UploadSceneType {
|
||||
KUPLOADSCENEH5LAUNCHCLIENTSHORTCUTKEYCTRLCV,
|
||||
KUPLOADSCENEAIODRAG,
|
||||
KUPLOADSCENEAIOFILESELECTOR,
|
||||
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV
|
||||
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV,
|
||||
}
|
||||
export interface StartFlashTaskRequests {
|
||||
screen: number; // 1 PC-QQ
|
||||
@@ -237,7 +237,7 @@ export interface StartFlashTaskRequests {
|
||||
}
|
||||
export enum BusiScene {
|
||||
KBUSISCENEINVALID,
|
||||
KBUSISCENEFLASHSCENE
|
||||
KBUSISCENEFLASHSCENE,
|
||||
}
|
||||
export interface FileListInfoRequests {
|
||||
seq: number, // 0
|
||||
@@ -274,7 +274,7 @@ export enum DownloadSceneType {
|
||||
KDOWNLOADSCENELINKOTHERINQQ,
|
||||
KDOWNLOADSCENESCANQRCODE,
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERCLIENT,
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA
|
||||
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA,
|
||||
}
|
||||
export interface FlashFileSetInfo {
|
||||
fileSetId: string,
|
||||
|
||||
@@ -22,7 +22,7 @@ export async function encodeSilk (filePath: string, TEMP_DIR: string, logger: Lo
|
||||
return {
|
||||
converted: true,
|
||||
path: pttPath,
|
||||
duration: duration,
|
||||
duration,
|
||||
};
|
||||
} else {
|
||||
let duration = 0;
|
||||
|
||||
@@ -2,22 +2,24 @@ import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import type { NapCatCore } from '@/napcat-core';
|
||||
import json5 from 'json5';
|
||||
import Ajv, { AnySchema, ValidateFunction } from 'ajv';
|
||||
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { TSchema } from '@sinclair/typebox';
|
||||
|
||||
export abstract class ConfigBase<T> {
|
||||
name: string;
|
||||
core: NapCatCore;
|
||||
configPath: string;
|
||||
configData: T = {} as T;
|
||||
ajv: Ajv;
|
||||
validate: ValidateFunction<T>;
|
||||
configSchema: TSchema;
|
||||
validate: TypeCheck<TSchema>;
|
||||
|
||||
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: AnySchema) {
|
||||
protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: TSchema) {
|
||||
this.name = name;
|
||||
this.core = core;
|
||||
this.configPath = configPath;
|
||||
this.ajv = new Ajv({ useDefaults: true, coerceTypes: true });
|
||||
this.validate = this.ajv.compile<T>(ConfigSchema);
|
||||
this.configSchema = ConfigSchema;
|
||||
this.validate = TypeCompiler.Compile(ConfigSchema);
|
||||
fs.mkdirSync(this.configPath, { recursive: true });
|
||||
this.read();
|
||||
}
|
||||
@@ -43,8 +45,12 @@ export abstract class ConfigBase<T> {
|
||||
private loadConfig (configPath: string): T {
|
||||
try {
|
||||
const newConfigData = json5.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
this.validate(newConfigData);
|
||||
this.configData = newConfigData;
|
||||
let data: unknown = newConfigData;
|
||||
data = Value.Parse(this.configSchema, data);
|
||||
if (!this.validate.Check(data)) {
|
||||
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
|
||||
}
|
||||
this.configData = data as T;
|
||||
this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData);
|
||||
return this.configData;
|
||||
} catch (e: unknown) {
|
||||
@@ -55,8 +61,12 @@ export abstract class ConfigBase<T> {
|
||||
|
||||
save (newConfigData: T = this.configData): void {
|
||||
const configPath = this.getConfigPath(this.core.selfInfo.uin);
|
||||
this.validate(newConfigData);
|
||||
this.configData = newConfigData;
|
||||
let data: unknown = newConfigData;
|
||||
data = Value.Parse(this.configSchema, data);
|
||||
if (!this.validate.Check(data)) {
|
||||
throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', '));
|
||||
}
|
||||
this.configData = data as T;
|
||||
try {
|
||||
fs.writeFileSync(configPath, JSON.stringify(this.configData, null, 2));
|
||||
} catch (e: unknown) {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { ConfigBase } from '@/napcat-core/helper/config-base';
|
||||
import { NapCatCore } from '@/napcat-core/index';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import Ajv, { AnySchema } from 'ajv';
|
||||
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { TSchema } from '@sinclair/typebox';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import json5 from 'json5';
|
||||
@@ -23,6 +25,7 @@ export const NapcatConfigSchema = Type.Object({
|
||||
packetBackend: Type.String({ default: 'auto' }),
|
||||
packetServer: Type.String({ default: '' }),
|
||||
o3HookMode: Type.Number({ default: 0 }),
|
||||
autoTimeSync: Type.Boolean({ default: true }),
|
||||
bypass: Type.Optional(BypassOptionsSchema),
|
||||
});
|
||||
|
||||
@@ -33,8 +36,6 @@ export type NapcatConfig = Static<typeof NapcatConfigSchema>;
|
||||
* 用于登录前(无 NapCatCore 实例时)的早期配置读取
|
||||
*/
|
||||
export function loadNapcatConfig (configPath: string): NapcatConfig {
|
||||
const ajv = new Ajv({ useDefaults: true, coerceTypes: true });
|
||||
const validate = ajv.compile<NapcatConfig>(NapcatConfigSchema);
|
||||
let data: Record<string, unknown> = {};
|
||||
try {
|
||||
const configFile = path.join(configPath, 'napcat.json');
|
||||
@@ -44,12 +45,12 @@ export function loadNapcatConfig (configPath: string): NapcatConfig {
|
||||
} catch {
|
||||
// 读取失败时使用 schema 默认值
|
||||
}
|
||||
validate(data);
|
||||
data = Value.Parse(NapcatConfigSchema, data) as Record<string, unknown>;
|
||||
return data as NapcatConfig;
|
||||
}
|
||||
|
||||
export class NapCatConfigLoader extends ConfigBase<NapcatConfig> {
|
||||
constructor (core: NapCatCore, configPath: string, schema: AnySchema) {
|
||||
constructor (core: NapCatCore, configPath: string, schema: TSchema) {
|
||||
super('napcat', core, configPath, schema);
|
||||
}
|
||||
}
|
||||
@@ -64,10 +64,12 @@ export class FFmpegService {
|
||||
}
|
||||
return this.adapter;
|
||||
}
|
||||
|
||||
public static async convertToNTSilkTct (inputFile: string, outputFile: string): Promise<void> {
|
||||
const adapter = await this.getAdapter();
|
||||
await adapter.convertToNTSilkTct(inputFile, outputFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 FFmpeg 路径并更新适配器
|
||||
* @deprecated 建议使用 init() 方法初始化
|
||||
|
||||
@@ -112,11 +112,11 @@ export class ForwardMsgBuilder {
|
||||
preview: m.valid ? m.toPreview() : '[该消息类型暂不支持查看]',
|
||||
})),
|
||||
})),
|
||||
source,
|
||||
news,
|
||||
summary,
|
||||
prompt,
|
||||
uuid,
|
||||
source,
|
||||
news,
|
||||
summary,
|
||||
prompt,
|
||||
uuid
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -59,13 +59,17 @@ class Subscription {
|
||||
export const logSubscription = new Subscription();
|
||||
|
||||
export class LogWrapper implements ILogWrapper {
|
||||
fileLogEnabled = true;
|
||||
fileLogEnabled = false;
|
||||
consoleLogEnabled = true;
|
||||
logger: winston.Logger;
|
||||
|
||||
private logPath: string;
|
||||
private fileTransportAdded = false;
|
||||
private fileLogLevel: string = LogLevel.DEBUG;
|
||||
|
||||
constructor (logDir: string) {
|
||||
const filename = `${getFormattedTimestamp()}.log`;
|
||||
const logPath = path.join(logDir, filename);
|
||||
this.logPath = path.join(logDir, filename);
|
||||
|
||||
this.logger = winston.createLogger({
|
||||
level: 'debug',
|
||||
@@ -77,12 +81,6 @@ export class LogWrapper implements ILogWrapper {
|
||||
})
|
||||
),
|
||||
transports: [
|
||||
new transports.File({
|
||||
filename: logPath,
|
||||
level: 'debug',
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}),
|
||||
new transports.Console({
|
||||
format: format.combine(
|
||||
format.colorize(),
|
||||
@@ -107,7 +105,7 @@ export class LogWrapper implements ILogWrapper {
|
||||
this.deleteOldLogFile(filePath, oneWeekAgo);
|
||||
});
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to read log directory', err);
|
||||
this.logError('Failed to read log directory', err);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,21 +115,22 @@ export class LogWrapper implements ILogWrapper {
|
||||
fs.unlink(filePath).catch((err) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
this.logger.warn(`File already deleted: ${filePath}`);
|
||||
this.logWarn(`File already deleted: ${filePath}`);
|
||||
} else {
|
||||
this.logger.error('Failed to delete old log file', err);
|
||||
this.logError('Failed to delete old log file', err);
|
||||
}
|
||||
} else {
|
||||
this.logger.info(`Deleted old log file: ${filePath}`);
|
||||
this.log(`Deleted old log file: ${filePath}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to get file stats', err);
|
||||
this.logError('Failed to get file stats', err);
|
||||
});
|
||||
}
|
||||
|
||||
setFileAndConsoleLogLevel (fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
|
||||
this.fileLogLevel = fileLogLevel;
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.level = fileLogLevel;
|
||||
@@ -148,6 +147,15 @@ export class LogWrapper implements ILogWrapper {
|
||||
|
||||
setFileLogEnabled (isEnabled: boolean) {
|
||||
this.fileLogEnabled = isEnabled;
|
||||
if (isEnabled && !this.fileTransportAdded) {
|
||||
this.fileTransportAdded = true;
|
||||
this.logger.add(new transports.File({
|
||||
filename: this.logPath,
|
||||
level: this.fileLogLevel,
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}));
|
||||
}
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.silent = !isEnabled;
|
||||
@@ -178,16 +186,18 @@ export class LogWrapper implements ILogWrapper {
|
||||
}
|
||||
|
||||
_log (level: LogLevel, ...args: any[]) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
if (this.consoleLogEnabled || this.fileLogEnabled) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
|
||||
log (...args: any[]) {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 服务器时间矫正 - 全局 Hook
|
||||
*
|
||||
* 保留 Date.now 原始引用,启动后通过 getServerTime 计算偏移量,
|
||||
* 直接覆盖 Date.now(),使全局所有调用自动获得矫正后的时间戳。
|
||||
*/
|
||||
|
||||
/** 原始 Date.now 引用,不受 hook 影响 */
|
||||
export const OriginalDateNow: () => number = Date.now.bind(Date);
|
||||
|
||||
/**
|
||||
* 初始化全局时间矫正,覆盖 Date.now()
|
||||
* @param getServerTimeFn 获取服务器时间的函数,返回毫秒级时间戳字符串
|
||||
* @returns 偏移量(毫秒)
|
||||
*/
|
||||
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
|
||||
const start = OriginalDateNow();
|
||||
const serverTimeStr = getServerTimeFn();
|
||||
const end = OriginalDateNow();
|
||||
const serverTimeMs = parseInt(serverTimeStr, 10);
|
||||
|
||||
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 补偿网络延迟:假定往返时间对称,服务器时间对应本地时间的中点 (start + end) / 2
|
||||
const offsetMs = Math.round(serverTimeMs - (start + end) / 2);
|
||||
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
Date.now = () => OriginalDateNow() + offsetMs;
|
||||
}
|
||||
|
||||
return offsetMs;
|
||||
}
|
||||
@@ -6,13 +6,13 @@ import { NTEventWrapper } from './event';
|
||||
* 创建 Service 方法的代理
|
||||
* 拦截所有方法调用,通过 EventWrapper 进行调用
|
||||
*/
|
||||
function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
|
||||
function createServiceMethodProxy<S extends keyof ServiceNamingMapping> (
|
||||
serviceName: S,
|
||||
originalService: ServiceNamingMapping[S],
|
||||
eventWrapper: NTEventWrapper
|
||||
): ServiceNamingMapping[S] {
|
||||
return new Proxy(originalService as object, {
|
||||
get(target, prop, receiver) {
|
||||
get (target, prop, receiver) {
|
||||
const originalValue = Reflect.get(target, prop, receiver);
|
||||
|
||||
// 如果不是函数,直接返回原始值
|
||||
@@ -50,7 +50,7 @@ function createServiceMethodProxy<S extends keyof ServiceNamingMapping>(
|
||||
* 第一层:拦截 getXXXService 方法
|
||||
* 第二层:拦截 Service 上的具体方法调用
|
||||
*/
|
||||
export function createSessionProxy(
|
||||
export function createSessionProxy (
|
||||
session: NodeIQQNTWrapperSession,
|
||||
eventWrapper: NTEventWrapper
|
||||
): NodeIQQNTWrapperSession {
|
||||
@@ -58,7 +58,7 @@ export function createSessionProxy(
|
||||
const serviceProxyCache = new Map<string, unknown>();
|
||||
|
||||
return new Proxy(session, {
|
||||
get(target, prop, receiver) {
|
||||
get (target, prop, receiver) {
|
||||
const propName = prop as string;
|
||||
|
||||
// 检查是否是 getXXXService 方法
|
||||
@@ -105,7 +105,7 @@ export function createSessionProxy(
|
||||
/**
|
||||
* 检查 Service 名称是否在已知的映射中
|
||||
*/
|
||||
function isKnownService(serviceName: string): serviceName is keyof ServiceNamingMapping {
|
||||
function isKnownService (serviceName: string): serviceName is keyof ServiceNamingMapping {
|
||||
const knownServices: string[] = [
|
||||
'NodeIKernelAvatarService',
|
||||
'NodeIKernelBuddyService',
|
||||
@@ -132,7 +132,7 @@ function isKnownService(serviceName: string): serviceName is keyof ServiceNaming
|
||||
* 创建带有 EventWrapper 集成的 InstanceContext
|
||||
* 这是推荐的使用方式,在创建 context 时自动代理 session
|
||||
*/
|
||||
export function createProxiedSession(
|
||||
export function createProxiedSession (
|
||||
session: NodeIQQNTWrapperSession,
|
||||
eventWrapper: NTEventWrapper
|
||||
): NodeIQQNTWrapperSession {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
NTQQWebApi,
|
||||
NTQQFlashApi,
|
||||
NTQQOnlineApi,
|
||||
NTQQDatabaseApi,
|
||||
} from '@/napcat-core/apis';
|
||||
import { NTQQCollectionApi } from '@/napcat-core/apis/collection';
|
||||
import {
|
||||
@@ -37,6 +38,7 @@ import { Napi2NativeLoader } from './packet/handler/napi2nativeLoader';
|
||||
import { container, ReceiverServiceRegistry } from './packet/handler/serviceRegister';
|
||||
import { appEvent } from './packet/handler/eventList';
|
||||
import { TypedEventEmitter } from './packet/handler/typeEvent';
|
||||
import { hookGlobalDateNow } from './helper/server-time';
|
||||
export * from './wrapper';
|
||||
export * from './types/index';
|
||||
export * from './services/index';
|
||||
@@ -49,6 +51,7 @@ export * from './helper/config';
|
||||
export * from './helper/config-base';
|
||||
export * from './helper/proxy-handler';
|
||||
export * from './helper/session-proxy';
|
||||
export * from './helper/server-time';
|
||||
|
||||
export enum NapCatCoreWorkingEnv {
|
||||
Unknown = 0,
|
||||
@@ -118,6 +121,8 @@ export class NapCatCore {
|
||||
selfInfo: SelfInfo;
|
||||
util: NodeQQNTWrapperUtil;
|
||||
configLoader: NapCatConfigLoader;
|
||||
/** 数据库 passphrase,由 OidbSvcTrpcTcp.0xcde_2 包获取 */
|
||||
dbPassphrase: string | undefined;
|
||||
|
||||
// 通过构造器递过去的 runtime info 应该尽量少
|
||||
constructor (context: InstanceContext, selfInfo: SelfInfo) {
|
||||
@@ -148,6 +153,7 @@ export class NapCatCore {
|
||||
GroupApi: new NTQQGroupApi(this.context, this),
|
||||
FlashApi: new NTQQFlashApi(this.context, this),
|
||||
OnlineApi: new NTQQOnlineApi(this.context, this),
|
||||
DatabaseApi: new NTQQDatabaseApi(this.context, this),
|
||||
};
|
||||
container.bind(NapCatCore).toConstantValue(this);
|
||||
container.bind(TypedEventEmitter).toConstantValue(this.event);
|
||||
@@ -169,6 +175,22 @@ export class NapCatCore {
|
||||
if (!fs.existsSync(this.NapCatTempPath)) {
|
||||
fs.mkdirSync(this.NapCatTempPath, { recursive: true });
|
||||
}
|
||||
// 通过 getServerTime 全局 hook Date.now() 矫正本地时间偏差
|
||||
// 可通过环境变量 NAPCAT_DISABLE_TIME_SYNC=1 或配置 autoTimeSync: false 禁用
|
||||
if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) {
|
||||
this.context.logger.log('[ServerTime] 自动对时已禁用');
|
||||
} else {
|
||||
try {
|
||||
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
|
||||
} else {
|
||||
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
|
||||
}
|
||||
}
|
||||
// 遍历this.apis[i].initApi 如果存在该函数进行async 调用
|
||||
for (const apiKey in this.apis) {
|
||||
const api = this.apis[apiKey as keyof StableNTApiWrapper];
|
||||
@@ -330,4 +352,5 @@ export interface StableNTApiWrapper {
|
||||
GroupApi: NTQQGroupApi;
|
||||
FlashApi: NTQQFlashApi,
|
||||
OnlineApi: NTQQOnlineApi,
|
||||
DatabaseApi: NTQQDatabaseApi,
|
||||
}
|
||||
@@ -53,6 +53,7 @@ export class NodeIKernelLoginListener {
|
||||
|
||||
onLoginState (..._args: any[]): any {
|
||||
}
|
||||
|
||||
onLoginRecordUpdate (..._args: any[]): any {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
{
|
||||
"name": "napcat-core",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
"name": "napcat-core",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.ts"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.ts"
|
||||
},
|
||||
"./*": {
|
||||
"import": "./*"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"winston": "^3.17.0",
|
||||
"json5": "^2.2.3",
|
||||
"inversify": "^7.10.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"@protobuf-ts/runtime": "^2.11.1",
|
||||
"ajv": "^8.13.0",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"file-type": "^21.0.0",
|
||||
"compressing": "^1.10.1",
|
||||
"napcat-image-size": "workspace:*",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
"./*": {
|
||||
"import": "./*"
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"@protobuf-ts/runtime": "^2.11.1",
|
||||
"@sinclair/typebox": "^0.34.38",
|
||||
"compressing": "^1.10.1",
|
||||
"file-type": "^21.0.0",
|
||||
"inversify": "^7.10.4",
|
||||
"json5": "^2.2.3",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-database": "workspace:*",
|
||||
"napcat-image-size": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
@@ -228,15 +228,17 @@ export class PacketOperationContext {
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async UploadForwardMsgV2 (msg: UploadForwardMsgParams[], groupUin: number = 0) {
|
||||
//await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源
|
||||
await Promise.allSettled(msg.map(async (item) => { return await this.SendPreprocess(item.actionMsg, groupUin); }));
|
||||
// await this.SendPreprocess(msg, groupUin);
|
||||
// 遍历上传资源(跳过已有原始数据的项)
|
||||
await Promise.allSettled(msg.filter(item => item.actionMsg).map(async (item) => { return await this.SendPreprocess(item.actionMsg!, groupUin); }));
|
||||
const req = trans.UploadForwardMsgV2.build(this.context.napcore.basicInfo.uid, msg, groupUin);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.UploadForwardMsg.parse(resp);
|
||||
return res.result.resId;
|
||||
}
|
||||
|
||||
async MoveGroupFile (
|
||||
groupUin: number,
|
||||
fileUUID: string,
|
||||
@@ -312,6 +314,15 @@ export class PacketOperationContext {
|
||||
}
|
||||
}
|
||||
|
||||
async FetchForwardMsgRaw (resId: string) {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, resId);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
const res = trans.DownloadForwardMsg.parse(resp);
|
||||
const inflate = gunzipSync(res.result.payload);
|
||||
const result = new NapProtoMsg(LongMsgResult).decode(inflate);
|
||||
return result.action;
|
||||
}
|
||||
|
||||
async FetchForwardMsg (res_id: string): Promise<RawMessage[]> {
|
||||
const req = trans.DownloadForwardMsg.build(this.context.napcore.basicInfo.uid, res_id);
|
||||
const resp = await this.context.client.sendOidbPacket(req, true);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as crypto from 'node:crypto';
|
||||
import * as zlib from 'node:zlib';
|
||||
import { NapProtoDecodeStructType, NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import {
|
||||
@@ -510,14 +511,14 @@ export class PacketMsgPttElement extends IPacketMsgElement<SendPttElement> {
|
||||
}
|
||||
|
||||
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
//return [];
|
||||
// return [];
|
||||
if (!this.msgInfo) return [];
|
||||
return [{
|
||||
commonElem: {
|
||||
serviceType: 48,
|
||||
pbElem: new NapProtoMsg(MsgInfo).encode(this.msgInfo),
|
||||
businessType: 22,
|
||||
}
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
@@ -665,11 +666,13 @@ export class PacketMsgMarkDownElement extends IPacketMsgElement<SendMarkdownElem
|
||||
export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsgElement> {
|
||||
resid: string;
|
||||
message: PacketMsg[];
|
||||
uuid: string;
|
||||
|
||||
constructor (rawElement: SendMultiForwardMsgElement, message?: PacketMsg[]) {
|
||||
super(rawElement);
|
||||
this.resid = rawElement.multiForwardMsgElement.resId;
|
||||
this.message = message ?? [];
|
||||
this.uuid = rawElement.multiForwardMsgElement.fileName || crypto.randomUUID();
|
||||
}
|
||||
|
||||
override buildElement (): NapProtoEncodeStructType<typeof Elem>[] {
|
||||
@@ -677,7 +680,7 @@ export class PacketMultiMsgElement extends IPacketMsgElement<SendMultiForwardMsg
|
||||
lightAppElem: {
|
||||
data: Buffer.concat([
|
||||
Buffer.from([0x01]),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message)), 'utf-8')),
|
||||
zlib.deflateSync(Buffer.from(JSON.stringify(ForwardMsgBuilder.fromPacketMsg(this.resid, this.message, undefined, undefined, undefined, undefined, this.uuid)), 'utf-8')),
|
||||
]),
|
||||
},
|
||||
}];
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import zlib from 'node:zlib';
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { NapProtoEncodeStructType, NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketBufBuilder, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import { PacketMsg } from '@/napcat-core/packet/message/message';
|
||||
|
||||
export interface UploadForwardMsgParams {
|
||||
actionCommand: string;
|
||||
actionMsg: PacketMsg[];
|
||||
actionMsg?: PacketMsg[];
|
||||
actionMsgBody?: NapProtoEncodeStructType<typeof proto.PushMsgBody>[];
|
||||
}
|
||||
class UploadForwardMsgV2 extends PacketTransformer<typeof proto.SendLongMsgResp> {
|
||||
build (selfUid: string, msg: UploadForwardMsgParams[], groupUin: number = 0): OidbPacket {
|
||||
const reqdata = msg.map((item) => ({
|
||||
actionCommand: item.actionCommand,
|
||||
actionData: {
|
||||
msgBody: this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg),
|
||||
}
|
||||
msgBody: item.actionMsgBody ?? this.msgBuilder.buildFakeMsg(selfUid, item.actionMsg ?? []),
|
||||
},
|
||||
}));
|
||||
const longMsgResultData = new NapProtoMsg(proto.LongMsgResult).encode(
|
||||
{
|
||||
|
||||
@@ -2,4 +2,4 @@ export { default as UploadForwardMsg } from './UploadForwardMsg';
|
||||
export { default as FetchGroupMessage } from './FetchGroupMessage';
|
||||
export { default as FetchC2CMessage } from './FetchC2CMessage';
|
||||
export { default as DownloadForwardMsg } from './DownloadForwardMsg';
|
||||
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
|
||||
export { default as UploadForwardMsgV2 } from './UploadForwardMsgV2';
|
||||
@@ -25,6 +25,7 @@ export * from './oidb/Oidb.0x929';
|
||||
export * from './oidb/Oidb.0xE37_1200';
|
||||
export * from './oidb/Oidb.0xE37_1700';
|
||||
export * from './oidb/Oidb.0XE37_800';
|
||||
export * from './oidb/Oidb.0xCDE_2';
|
||||
export * from './oidb/Oidb.0xEB7';
|
||||
export * from './oidb/Oidb.0xED3_1';
|
||||
export * from './oidb/Oidb.0XFE1_2';
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { ProtoField, ScalarType } from 'napcat-protobuf';
|
||||
|
||||
// OidbSvcTrpcTcp.0xcde_2 响应体
|
||||
// body.field2.field1 为目标字符串值
|
||||
export const OidbSvcTrpcTcp0XCDE_2RespBodyInner = {
|
||||
value: ProtoField(1, ScalarType.STRING),
|
||||
};
|
||||
|
||||
export const OidbSvcTrpcTcp0XCDE_2RespBody = {
|
||||
inner: ProtoField(2, () => OidbSvcTrpcTcp0XCDE_2RespBodyInner),
|
||||
};
|
||||
@@ -32,7 +32,7 @@ export interface NodeIKernelGroupService {
|
||||
getAllGroupPrivilegeFlag (troopUinList: string[], serviceType: number): Promise<unknown>;
|
||||
// <---
|
||||
getGroupExt0xEF0Info (enableGroupCodes: string[], bannedGroupCodes: string[], filter: GroupExt0xEF0InfoFilter, forceFetch: boolean):
|
||||
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
|
||||
Promise<GeneralCallResult & { result: { groupExtInfos: Map<string, unknown>; }; }>;
|
||||
|
||||
kickMemberV2 (param: KickMemberV2Req): Promise<GeneralCallResult>;
|
||||
|
||||
|
||||
@@ -29,10 +29,11 @@ export interface PasswordLoginArgType {
|
||||
uin: string;
|
||||
passwordMd5: string;// passwMD5
|
||||
step: number;// 猜测是需要二次认证 参数 一次为0
|
||||
newDeviceLoginSig: string;
|
||||
proofWaterSig: string;
|
||||
proofWaterRand: string;
|
||||
proofWaterSid: string;
|
||||
newDeviceLoginSig: Uint8Array;
|
||||
proofWaterSig: Uint8Array;
|
||||
proofWaterRand: Uint8Array;
|
||||
proofWaterSid: Uint8Array;
|
||||
unusualDeviceCheckSig: Uint8Array;
|
||||
}
|
||||
|
||||
export interface LoginListItem {
|
||||
|
||||
@@ -688,14 +688,14 @@ export interface NodeIKernelMsgService {
|
||||
msgSeq: string;
|
||||
msgRandom: string;
|
||||
}>, DataMigrationResourceInfo: {
|
||||
extraData: string;
|
||||
filePath: string;
|
||||
fileSize: string;
|
||||
msgRandom: string;
|
||||
msgSeq: string;
|
||||
msgSubType: number;
|
||||
msgType: number;
|
||||
}): unknown;
|
||||
extraData: string;
|
||||
filePath: string;
|
||||
fileSize: string;
|
||||
msgRandom: string;
|
||||
msgSeq: string;
|
||||
msgSubType: number;
|
||||
msgType: number;
|
||||
}): unknown;
|
||||
|
||||
dataMigrationGetResourceLocalDestinyPath (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export interface NodeIKernelStorageCleanService {
|
||||
// "C:\\Users\\nanaeo\\AppData\\Roaming\\QQ\\Partitions\\qqnt_9212"
|
||||
// ]
|
||||
// ]
|
||||
addCacheScanedPaths (paths: Map<`tmp` | `SilentCacheappSessionPartation9212` | `hotUpdate`, unknown>): unknown;
|
||||
addCacheScanedPaths (paths: Map<'tmp' | 'SilentCacheappSessionPartation9212' | 'hotUpdate', unknown>): unknown;
|
||||
|
||||
addFilesScanedPaths (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"name": "napcat-database",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit --skipLibCheck -p tsconfig.json"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./src/index.ts"
|
||||
},
|
||||
"./src/*": {
|
||||
"import": "./src/*"
|
||||
}
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/** 文件头部扩展区大小 */
|
||||
export const EXT_HEADER_SIZE = 1024;
|
||||
|
||||
/** SQLCipher 页大小 */
|
||||
export const PAGE_SIZE = 4096;
|
||||
|
||||
/** PBKDF2 salt 长度 */
|
||||
export const SALT_SIZE = 16;
|
||||
|
||||
/** AES-256 密钥长度 */
|
||||
export const KEY_SIZE = 32;
|
||||
|
||||
/** AES-CBC IV 长度 */
|
||||
export const IV_SIZE = 16;
|
||||
|
||||
/** HMAC-SHA1 长度 */
|
||||
export const HMAC_SIZE = 20;
|
||||
|
||||
/** 每页保留区大小: IV(16) + HMAC_SHA1(20) + pad(12) = 48 */
|
||||
export const RESERVE_SIZE = 48;
|
||||
|
||||
/** PBKDF2 主密钥迭代次数 */
|
||||
export const KDF_ITERATIONS = 4000;
|
||||
|
||||
/** PBKDF2 HMAC 密钥迭代次数 */
|
||||
export const FAST_ITERATIONS = 2;
|
||||
|
||||
/** HMAC salt XOR 掩码 */
|
||||
export const HMAC_MASK = 0x3a;
|
||||
|
||||
/** SQLite 加密文件头 */
|
||||
export const SQLITE_HEADER = Buffer.from('SQLite header 3\0');
|
||||
|
||||
/** SQLite 明文文件头 */
|
||||
export const SQLITE_FORMAT = Buffer.from('SQLite format 3\0');
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* 密钥派生
|
||||
* enc_key = PBKDF2_HMAC_SHA512(passphrase, salt, 4000, 32)
|
||||
* hmac_key = PBKDF2_HMAC_SHA512(enc_key, salt ^ 0x3a, 2, 32)
|
||||
*/
|
||||
|
||||
import { pbkdf2Sync } from 'node:crypto';
|
||||
import {
|
||||
KEY_SIZE,
|
||||
KDF_ITERATIONS,
|
||||
FAST_ITERATIONS,
|
||||
HMAC_MASK,
|
||||
} from './constants';
|
||||
|
||||
export interface DerivedKeys {
|
||||
encKey: Buffer;
|
||||
hmacKey: Buffer;
|
||||
}
|
||||
export function deriveKeys (passphrase: Buffer, salt: Buffer): DerivedKeys {
|
||||
const encKey = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, KEY_SIZE, 'sha512');
|
||||
|
||||
const hmacSalt = Buffer.alloc(salt.length);
|
||||
for (let i = 0; i < salt.length; i++) {
|
||||
hmacSalt[i] = salt[i]! ^ HMAC_MASK;
|
||||
}
|
||||
const hmacKey = pbkdf2Sync(encKey, hmacSalt, FAST_ITERATIONS, KEY_SIZE, 'sha512');
|
||||
|
||||
return { encKey, hmacKey };
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { createDecipheriv } from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import {
|
||||
EXT_HEADER_SIZE,
|
||||
PAGE_SIZE,
|
||||
SALT_SIZE,
|
||||
IV_SIZE,
|
||||
RESERVE_SIZE,
|
||||
SQLITE_HEADER,
|
||||
SQLITE_FORMAT,
|
||||
} from './constants';
|
||||
import { deriveKeys } from './crypto';
|
||||
|
||||
/**
|
||||
* 解密单个 SQLCipher 页面
|
||||
* @param pageData 原始页数据 (4096 字节)
|
||||
* @param encKey AES-256 密钥
|
||||
* @param skipSalt 页 1 需跳过前 16 字节 salt
|
||||
*/
|
||||
function decryptPage (pageData: Buffer, encKey: Buffer, skipSalt: number = 0): Buffer {
|
||||
const data = pageData.subarray(skipSalt);
|
||||
const contentLen = data.length - RESERVE_SIZE;
|
||||
const encrypted = data.subarray(0, contentLen);
|
||||
const iv = data.subarray(contentLen, contentLen + IV_SIZE);
|
||||
|
||||
const decipher = createDecipheriv('aes-256-cbc', encKey, iv);
|
||||
decipher.setAutoPadding(false);
|
||||
return Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文件是否为 NTQQ 加密数据库
|
||||
*/
|
||||
export function isEncryptedNTDB (fileData: Buffer): boolean {
|
||||
if (fileData.length < EXT_HEADER_SIZE + PAGE_SIZE) return false;
|
||||
return fileData.subarray(0, 16).equals(SQLITE_HEADER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将加密的 NTQQ 数据库解密为标准 SQLite 数据库
|
||||
* @param fileData 完整的加密数据库文件内容
|
||||
* @param passphrase 服务端返回的密钥口令
|
||||
* @returns 解密后的 SQLite 数据库 Buffer,失败返回 null
|
||||
*/
|
||||
export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer | null {
|
||||
if (!isEncryptedNTDB(fileData)) return null;
|
||||
|
||||
const scData = fileData.subarray(EXT_HEADER_SIZE);
|
||||
const totalPages = Math.floor(scData.length / PAGE_SIZE);
|
||||
if (totalPages === 0) return null;
|
||||
|
||||
const salt = scData.subarray(0, SALT_SIZE);
|
||||
const { encKey } = deriveKeys(passphrase, salt);
|
||||
|
||||
const output = Buffer.alloc(totalPages * PAGE_SIZE);
|
||||
let offset = 0;
|
||||
|
||||
for (let pgno = 1; pgno <= totalPages; pgno++) {
|
||||
const pageOffset = (pgno - 1) * PAGE_SIZE;
|
||||
const rawPage = scData.subarray(pageOffset, pageOffset + PAGE_SIZE);
|
||||
const skip = pgno === 1 ? SALT_SIZE : 0;
|
||||
const decrypted = decryptPage(rawPage, encKey, skip);
|
||||
|
||||
if (pgno === 1) {
|
||||
// 重建 Page 1: SQLite 标准文件头 + 解密内容
|
||||
SQLITE_FORMAT.copy(output, 0);
|
||||
decrypted.copy(output, 16);
|
||||
// 修正 page_size 字段 (offset 16-17, big-endian)
|
||||
output.writeUInt16BE(PAGE_SIZE, 16);
|
||||
// 保留原始 reserved-bytes-per-page 值 (byte 20)
|
||||
// NTQQ SQLCipher 使用 reserved=80 用于 B-tree 布局 (usable=4016)
|
||||
// 即使加密保留区 (IV+HMAC) 实际只有 48 字节
|
||||
// 清零会导致 SQLite 误判溢出指针,报 "database disk image is malformed"
|
||||
offset = PAGE_SIZE;
|
||||
} else {
|
||||
decrypted.copy(output, offset);
|
||||
offset += PAGE_SIZE;
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密数据库文件并写入输出路径
|
||||
* @param inputPath 加密数据库路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param outputPath 输出路径 (默认: 原路径加 _decrypted 后缀)
|
||||
* @returns 输出路径,失败返回 null
|
||||
*/
|
||||
export function decryptDatabaseFile (
|
||||
inputPath: string,
|
||||
passphrase: Buffer,
|
||||
outputPath?: string
|
||||
): string | null {
|
||||
const fileData = fs.readFileSync(inputPath);
|
||||
const result = decryptDatabase(fileData, passphrase);
|
||||
if (!result) return null;
|
||||
|
||||
if (!outputPath) {
|
||||
const dotIdx = inputPath.lastIndexOf('.');
|
||||
outputPath = dotIdx > 0
|
||||
? inputPath.substring(0, dotIdx) + '_decrypted' + inputPath.substring(dotIdx)
|
||||
: inputPath + '_decrypted';
|
||||
}
|
||||
|
||||
fs.writeFileSync(outputPath, result);
|
||||
return outputPath;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
export { deriveKeys, type DerivedKeys } from './crypto';
|
||||
export { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
|
||||
export {
|
||||
checkSqliteAvailable,
|
||||
DatabaseHandle,
|
||||
openDatabase,
|
||||
decryptAndOpen,
|
||||
listTablesFromBuffer,
|
||||
listTablesFromFile,
|
||||
readSingleDatabase,
|
||||
scanAllDatabases,
|
||||
formatScanResults,
|
||||
type TableInfo,
|
||||
type ColumnInfo,
|
||||
type DatabaseScanResult,
|
||||
type DatabaseReadOptions,
|
||||
} from './reader';
|
||||
export {
|
||||
EXT_HEADER_SIZE,
|
||||
PAGE_SIZE,
|
||||
SALT_SIZE,
|
||||
KEY_SIZE,
|
||||
IV_SIZE,
|
||||
HMAC_SIZE,
|
||||
RESERVE_SIZE,
|
||||
KDF_ITERATIONS,
|
||||
FAST_ITERATIONS,
|
||||
HMAC_MASK,
|
||||
} from './constants';
|
||||
@@ -0,0 +1,425 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import { decryptDatabase, decryptDatabaseFile, isEncryptedNTDB } from './decrypt';
|
||||
|
||||
type DatabaseSyncType = import('node:sqlite').DatabaseSync;
|
||||
type DatabaseSyncCtor = new (path: string, options?: { readOnly?: boolean; }) => DatabaseSyncType;
|
||||
type SQLInputValue = import('node:sqlite').SQLInputValue;
|
||||
|
||||
let _DatabaseSync: DatabaseSyncCtor | null = null;
|
||||
let _sqliteChecked = false;
|
||||
|
||||
async function loadSqlite (): Promise<DatabaseSyncCtor | null> {
|
||||
if (_sqliteChecked) return _DatabaseSync;
|
||||
_sqliteChecked = true;
|
||||
try {
|
||||
const mod = await import('node:sqlite');
|
||||
_DatabaseSync = mod.DatabaseSync as unknown as DatabaseSyncCtor;
|
||||
return _DatabaseSync;
|
||||
} catch {
|
||||
_DatabaseSync = null;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getDatabaseSync (): DatabaseSyncCtor {
|
||||
if (!_DatabaseSync) {
|
||||
throw new Error(
|
||||
'node:sqlite 不可用。请使用 Node.js 22+ 并添加 --experimental-sqlite 标志,' +
|
||||
'或调用 checkSqliteAvailable() 检查可用性。'
|
||||
);
|
||||
}
|
||||
return _DatabaseSync;
|
||||
}
|
||||
|
||||
export async function checkSqliteAvailable (): Promise<boolean> {
|
||||
const ctor = await loadSqlite();
|
||||
return ctor !== null;
|
||||
}
|
||||
|
||||
// ======================== 数据库连接管理 ========================
|
||||
|
||||
/** 数据库连接句柄,封装 DatabaseSync 实例 */
|
||||
export class DatabaseHandle {
|
||||
private db: DatabaseSyncType;
|
||||
private _closed = false;
|
||||
readonly filePath: string;
|
||||
readonly readOnly: boolean;
|
||||
|
||||
constructor (filePath: string, readOnly = false) {
|
||||
const DB = getDatabaseSync();
|
||||
this.db = new DB(filePath, { readOnly });
|
||||
this.filePath = filePath;
|
||||
this.readOnly = readOnly;
|
||||
}
|
||||
|
||||
/** 数据库是否已关闭 */
|
||||
get closed (): boolean {
|
||||
return this._closed;
|
||||
}
|
||||
|
||||
private ensureOpen (): void {
|
||||
if (this._closed) throw new Error('数据库已关闭');
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SELECT 查询,返回所有结果行
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数 (位置参数数组 或 命名参数对象)
|
||||
*/
|
||||
query<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T[] {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.all(...params) as T[];
|
||||
}
|
||||
return stmt.all(params) as T[];
|
||||
}
|
||||
return stmt.all() as T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行 SELECT 查询,仅返回第一行
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
*/
|
||||
queryOne<T = Record<string, unknown>> (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): T | undefined {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.get(...params) as T | undefined;
|
||||
}
|
||||
return stmt.get(params) as T | undefined;
|
||||
}
|
||||
return stmt.get() as T | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行非查询 SQL (INSERT/UPDATE/DELETE/CREATE 等)
|
||||
* @param sql SQL 语句
|
||||
* @param params 绑定参数
|
||||
* @returns 受影响的行数信息
|
||||
*/
|
||||
execute (sql: string, params?: SQLInputValue[] | Record<string, SQLInputValue>): { changes: number | bigint; lastInsertRowid: number | bigint; } {
|
||||
this.ensureOpen();
|
||||
const stmt = this.db.prepare(sql);
|
||||
if (params) {
|
||||
if (Array.isArray(params)) {
|
||||
return stmt.run(...params);
|
||||
}
|
||||
return stmt.run(params);
|
||||
}
|
||||
return stmt.run();
|
||||
}
|
||||
|
||||
/** 列出所有表的信息 */
|
||||
listTables (): TableInfo[] {
|
||||
this.ensureOpen();
|
||||
return extractTablesInfo(this.db);
|
||||
}
|
||||
|
||||
/** 获取指定表的列信息 */
|
||||
getTableColumns (tableName: string): ColumnInfo[] {
|
||||
this.ensureOpen();
|
||||
const cols = this.db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
|
||||
cid: number; name: string; type: string; notnull: number; pk: number;
|
||||
}[];
|
||||
return cols.map(col => ({
|
||||
cid: col.cid,
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
notnull: col.notnull === 1,
|
||||
pk: col.pk === 1,
|
||||
}));
|
||||
}
|
||||
|
||||
/** 获取表的行数 */
|
||||
getRowCount (tableName: string): number {
|
||||
this.ensureOpen();
|
||||
const cnt = this.db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
|
||||
return cnt?.cnt ?? 0;
|
||||
}
|
||||
|
||||
/** 关闭数据库连接 */
|
||||
close (): void {
|
||||
if (!this._closed) {
|
||||
this.db.close();
|
||||
this._closed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个已解密的 SQLite 数据库文件
|
||||
* @param filePath 解密后的 .db 文件路径
|
||||
* @param readOnly 是否以只读模式打开 (默认 true)
|
||||
*/
|
||||
export function openDatabase (filePath: string, readOnly = true): DatabaseHandle {
|
||||
return new DatabaseHandle(filePath, readOnly);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并打开一个加密的 NTQQ 数据库
|
||||
* @param dbPath 加密数据库路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param cacheDir 解密缓存目录 (可选)
|
||||
* @param readOnly 是否只读 (默认 true)
|
||||
*/
|
||||
export function decryptAndOpen (
|
||||
dbPath: string,
|
||||
passphrase: Buffer,
|
||||
cacheDir?: string,
|
||||
readOnly = true
|
||||
): DatabaseHandle {
|
||||
const filename = path.basename(dbPath);
|
||||
|
||||
if (cacheDir) {
|
||||
const cachedPath = path.join(cacheDir, filename);
|
||||
// 已存在缓存直接打开
|
||||
if (fs.existsSync(cachedPath)) {
|
||||
return new DatabaseHandle(cachedPath, readOnly);
|
||||
}
|
||||
fs.mkdirSync(cacheDir, { recursive: true });
|
||||
const outPath = decryptDatabaseFile(dbPath, passphrase, cachedPath);
|
||||
if (!outPath) throw new Error(`解密失败: ${dbPath}`);
|
||||
return new DatabaseHandle(outPath, readOnly);
|
||||
}
|
||||
|
||||
// 无缓存目录: 解密到临时文件
|
||||
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
|
||||
const fileData = fs.readFileSync(dbPath);
|
||||
const decryptedBuf = decryptDatabase(fileData, passphrase);
|
||||
if (!decryptedBuf) throw new Error(`解密失败: ${dbPath}`);
|
||||
fs.writeFileSync(tmpPath, decryptedBuf);
|
||||
return new DatabaseHandle(tmpPath, readOnly);
|
||||
}
|
||||
|
||||
/** 单个数据库表信息 */
|
||||
export interface TableInfo {
|
||||
name: string;
|
||||
type: string; // 'table' | 'view' | ...
|
||||
rowCount: number;
|
||||
columns: ColumnInfo[];
|
||||
}
|
||||
|
||||
/** 列信息 */
|
||||
export interface ColumnInfo {
|
||||
cid: number;
|
||||
name: string;
|
||||
type: string;
|
||||
notnull: boolean;
|
||||
pk: boolean;
|
||||
}
|
||||
|
||||
/** 单个数据库扫描结果 */
|
||||
export interface DatabaseScanResult {
|
||||
/** 数据库文件名 */
|
||||
filename: string;
|
||||
/** 原始加密文件路径 */
|
||||
sourcePath: string;
|
||||
/** 解密后缓存文件路径 (仅当指定了 cacheDir 时) */
|
||||
cachePath?: string;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
tables: TableInfo[];
|
||||
}
|
||||
|
||||
/** 扫描/读取选项 */
|
||||
export interface DatabaseReadOptions {
|
||||
/** 解密后数据库缓存目录,不设置则使用临时文件 */
|
||||
cacheDir?: string;
|
||||
/** 是否跳过已存在的缓存文件 (默认 true) */
|
||||
skipExistingCache?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 DatabaseSync 对象提取表信息
|
||||
*/
|
||||
function extractTablesInfo (db: DatabaseSyncType): TableInfo[] {
|
||||
const tables: TableInfo[] = [];
|
||||
|
||||
const masterRows = db.prepare(
|
||||
"SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY name"
|
||||
).all() as { name: string; type: string; }[];
|
||||
|
||||
for (const { name: tableName, type: tableType } of masterRows) {
|
||||
// 获取列信息
|
||||
const columns: ColumnInfo[] = [];
|
||||
try {
|
||||
const cols = db.prepare(`PRAGMA table_info([${tableName}])`).all() as {
|
||||
cid: number; name: string; type: string; notnull: number; pk: number;
|
||||
}[];
|
||||
for (const col of cols) {
|
||||
columns.push({
|
||||
cid: col.cid,
|
||||
name: col.name,
|
||||
type: col.type,
|
||||
notnull: col.notnull === 1,
|
||||
pk: col.pk === 1,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// PRAGMA 可能对某些表失败
|
||||
}
|
||||
|
||||
// 获取行数
|
||||
let rowCount = 0;
|
||||
try {
|
||||
const cnt = db.prepare(`SELECT count(*) as cnt FROM [${tableName}]`).get() as { cnt: number; } | undefined;
|
||||
rowCount = cnt?.cnt ?? 0;
|
||||
} catch {
|
||||
rowCount = -1;
|
||||
}
|
||||
|
||||
tables.push({
|
||||
name: tableName,
|
||||
type: tableType,
|
||||
rowCount,
|
||||
columns,
|
||||
});
|
||||
}
|
||||
|
||||
return tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开一个解密后的 SQLite 文件,列出所有表和列信息
|
||||
*/
|
||||
export function listTablesFromFile (filePath: string): TableInfo[] {
|
||||
const DB = getDatabaseSync();
|
||||
const db = new DB(filePath, { readOnly: true });
|
||||
try {
|
||||
return extractTablesInfo(db);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
export function listTablesFromBuffer (data: Buffer): TableInfo[] {
|
||||
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
|
||||
try {
|
||||
fs.writeFileSync(tmpPath, data);
|
||||
return listTablesFromFile(tmpPath);
|
||||
} finally {
|
||||
try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密并读取单个数据库文件
|
||||
*
|
||||
* @param dbPath 加密数据库文件路径
|
||||
* @param passphrase 密钥口令
|
||||
* @param options 可选配置 (缓存目录等)
|
||||
* @returns 数据库扫描结果
|
||||
*/
|
||||
export function readSingleDatabase (
|
||||
dbPath: string,
|
||||
passphrase: Buffer,
|
||||
options?: DatabaseReadOptions
|
||||
): DatabaseScanResult {
|
||||
const filename = path.basename(dbPath);
|
||||
const result: DatabaseScanResult = {
|
||||
filename,
|
||||
sourcePath: dbPath,
|
||||
success: false,
|
||||
tables: [],
|
||||
};
|
||||
|
||||
try {
|
||||
// 如果指定了缓存目录,且缓存文件已存在,直接读取
|
||||
if (options?.cacheDir) {
|
||||
const cachedPath = path.join(options.cacheDir, filename);
|
||||
result.cachePath = cachedPath;
|
||||
|
||||
if (options?.skipExistingCache !== false && fs.existsSync(cachedPath)) {
|
||||
result.tables = listTablesFromFile(cachedPath);
|
||||
result.success = true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const fileData = fs.readFileSync(dbPath);
|
||||
if (!isEncryptedNTDB(fileData)) {
|
||||
result.error = 'Not an encrypted NTQQ database';
|
||||
return result;
|
||||
}
|
||||
|
||||
// 有缓存目录: 解密写入文件再读取
|
||||
if (options?.cacheDir) {
|
||||
fs.mkdirSync(options.cacheDir, { recursive: true });
|
||||
const outPath = decryptDatabaseFile(dbPath, passphrase, result.cachePath);
|
||||
if (!outPath) {
|
||||
result.error = 'Decryption failed';
|
||||
return result;
|
||||
}
|
||||
result.cachePath = outPath;
|
||||
result.tables = listTablesFromFile(outPath);
|
||||
} else {
|
||||
// 无缓存目录: 解密到内存再用临时文件读取
|
||||
const decryptedBuf = decryptDatabase(fileData, passphrase);
|
||||
if (!decryptedBuf) {
|
||||
result.error = 'Decryption returned null';
|
||||
return result;
|
||||
}
|
||||
result.tables = listTablesFromBuffer(decryptedBuf);
|
||||
}
|
||||
|
||||
result.success = true;
|
||||
} catch (e) {
|
||||
result.error = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function scanAllDatabases (
|
||||
dbDir: string,
|
||||
passphrase: Buffer,
|
||||
options?: DatabaseReadOptions
|
||||
): DatabaseScanResult[] {
|
||||
const results: DatabaseScanResult[] = [];
|
||||
|
||||
if (!fs.existsSync(dbDir)) return results;
|
||||
|
||||
const files = fs.readdirSync(dbDir).filter(f => f.endsWith('.db')).sort();
|
||||
|
||||
for (const filename of files) {
|
||||
const filePath = path.join(dbDir, filename);
|
||||
const result = readSingleDatabase(filePath, passphrase, options);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化扫描结果为可读字符串
|
||||
*/
|
||||
export function formatScanResults (results: DatabaseScanResult[]): string {
|
||||
const lines: string[] = [];
|
||||
let totalTables = 0;
|
||||
let successCount = 0;
|
||||
|
||||
for (const db of results) {
|
||||
if (db.success) {
|
||||
successCount++;
|
||||
const cacheNote = db.cachePath ? ` → ${db.cachePath}` : '';
|
||||
lines.push(`=== ${db.filename} (${db.tables.length} tables)${cacheNote} ===`);
|
||||
for (const table of db.tables) {
|
||||
totalTables++;
|
||||
const colList = table.columns.map(c => `${c.name}:${c.type || '?'}`).join(', ');
|
||||
lines.push(` ${table.name}: ${table.rowCount} rows [${colList}]`);
|
||||
}
|
||||
} else {
|
||||
lines.push(`=== ${db.filename}: SKIP (${db.error}) ===`);
|
||||
}
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
lines.push(`Summary: ${successCount}/${results.length} databases decrypted, ${totalTables} total tables`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist"
|
||||
]
|
||||
}
|
||||
@@ -47,12 +47,12 @@ const itemsToCopy = [
|
||||
'package.json',
|
||||
'QBar.dll',
|
||||
'wrapper.node',
|
||||
'LightQuic.dll'
|
||||
'LightQuic.dll',
|
||||
];
|
||||
|
||||
const win64ItemsToCopy = [
|
||||
'SSOShareInfoHelper64.dll',
|
||||
'parent-ipc-core-x64.dll'
|
||||
'parent-ipc-core-x64.dll',
|
||||
];
|
||||
|
||||
async function copyAll () {
|
||||
|
||||
@@ -12,6 +12,8 @@ import { proxiedListenerOf } from '@/napcat-core/helper/proxy-handler';
|
||||
import { statusHelperSubscription } from '@/napcat-core/helper/status';
|
||||
import { applyPendingUpdates } from '@/napcat-webui-backend/src/api/UpdateNapCat';
|
||||
import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbSvcTrpcTcpBase, OidbSvcTrpcTcp0XCDE_2RespBody } from '@/napcat-core/packet/transformer/proto';
|
||||
|
||||
// Framework ES入口文件
|
||||
export async function getWebUiUrl () {
|
||||
@@ -44,7 +46,7 @@ export async function NCoreInitFramework (
|
||||
const nativePacketHandler = new NativePacketHandler({ logger }); // 初始化 NativePacketHandler 用于后续使用
|
||||
const napi2nativeLoader = new Napi2NativeLoader({ logger }); // 初始化 Napi2NativeLoader 用于后续使用
|
||||
const napcatConfig = loadNapcatConfig(pathWrapper.configPath);
|
||||
//console.log('[NapCat] [Napi2NativeLoader]', napi2nativeLoader.nativeExports.enableAllBypasses?.());
|
||||
// console.log('[NapCat] [Napi2NativeLoader]', napi2nativeLoader.nativeExports.enableAllBypasses?.());
|
||||
if (process.env['NAPCAT_DISABLE_BYPASS'] !== '1') {
|
||||
const bypassOptions = napcatConfig.bypass ?? {};
|
||||
const bypassEnabled = napi2nativeLoader.nativeExports.enableAllBypasses?.(bypassOptions);
|
||||
@@ -58,21 +60,51 @@ export async function NCoreInitFramework (
|
||||
// nativePacketHandler.onAll((packet) => {
|
||||
// console.log('[Packet]', packet.uin, packet.cmd, packet.hex_data);
|
||||
// });
|
||||
await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion(), napcatConfig.o3HookMode === 1 ? true : false);
|
||||
await nativePacketHandler.init(basicInfoWrapper.getFullQQVersion(), napcatConfig.o3HookMode === 1);
|
||||
// 在 init 之后注册监听器
|
||||
|
||||
// 登录前监听 OidbSvcTrpcTcp.0xcde_2 数据包,获取数据库 passphrase
|
||||
let dbPassphrase: string | undefined;
|
||||
nativePacketHandler.onCmd('OidbSvcTrpcTcp.0xcde_2', ({ type, hex_data }) => {
|
||||
if (type !== 1) return; // 仅处理接收方向
|
||||
try {
|
||||
const raw = Buffer.from(hex_data, 'hex');
|
||||
const base = new NapProtoMsg(OidbSvcTrpcTcpBase).decode(raw);
|
||||
if (base.body && base.body.length > 0) {
|
||||
const body = new NapProtoMsg(OidbSvcTrpcTcp0XCDE_2RespBody).decode(base.body);
|
||||
if (body.inner?.value) {
|
||||
dbPassphrase = body.inner.value;
|
||||
logger.log('[NapCat] 已启用数据库辅助支持能力');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.logError('[NapCat] [0xCDE_2] 解析失败:', e);
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化 FFmpeg 服务
|
||||
await FFmpegService.init(pathWrapper.binaryPath, logger);
|
||||
|
||||
// 提前启动 WebUI,使其在登录前可用,支持通过 WebUI 操控登录过程
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// 直到登录成功后,执行下一步
|
||||
// const selfInfo = {
|
||||
// uid: 'u_FUSS0_x06S_9Tf4na_WpUg',
|
||||
// uin: '3684714082',
|
||||
// nick: '',
|
||||
// online: true
|
||||
// }
|
||||
const selfInfo = await new Promise<SelfInfo>((resolve) => {
|
||||
const loginContext = { isLogined: false };
|
||||
|
||||
const loginListener = new NodeIKernelLoginListener();
|
||||
|
||||
loginListener.onUserLoggedIn = (userid: string) => {
|
||||
const tips = `当前账号(${userid})已登录,无法重复登录`;
|
||||
logger.logError(tips);
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeLoginSucceed = async (loginResult) => {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
await new Promise<void>(resolve => {
|
||||
registerInitCallback(() => resolve());
|
||||
});
|
||||
@@ -83,18 +115,78 @@ export async function NCoreInitFramework (
|
||||
online: true,
|
||||
});
|
||||
};
|
||||
|
||||
loginListener.onQRCodeGetPicture = ({ qrcodeUrl }) => {
|
||||
WebUiDataRuntime.setQQLoginQrcodeURL(qrcodeUrl);
|
||||
logger.log('[NapCat] [Framework] 二维码已更新, URL:', qrcodeUrl);
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionFailed = (errType: number, errCode: number) => {
|
||||
if (!loginContext.isLogined) {
|
||||
logger.logError('[NapCat] [Framework] [Login] QRCode Session Failed, ErrType:', errType, 'ErrCode:', errCode);
|
||||
if (errType === 1 && errCode === 3) {
|
||||
WebUiDataRuntime.setQQLoginError('二维码已过期,请刷新');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loginListener.onLoginFailed = (...args) => {
|
||||
const errInfo = JSON.stringify(args);
|
||||
logger.logError('[NapCat] [Framework] [Login] Login Failed, ErrInfo:', errInfo);
|
||||
WebUiDataRuntime.setQQLoginError(`登录失败: ${errInfo}`);
|
||||
};
|
||||
|
||||
loginListener.onLoginConnected = () => {
|
||||
logger.log('[NapCat] [Framework] 登录服务已连接');
|
||||
// 注册 WebUI 登录操作回调
|
||||
registerWebUiLoginCallbacks(loginService, loginContext, logger);
|
||||
// 获取历史登录列表供 WebUI 使用
|
||||
loginService.getLoginList().then((res) => {
|
||||
const list = res.LocalLoginInfoList.filter((item) => item.isQuickLogin);
|
||||
WebUiDataRuntime.setQQQuickLoginList(list.map((item) => item.uin.toString()));
|
||||
WebUiDataRuntime.setQQNewLoginList(list);
|
||||
}).catch(e => logger.logError('[NapCat] [Framework] 获取登录列表失败:', e));
|
||||
};
|
||||
|
||||
loginListener.onQRCodeSessionUserScaned = () => {
|
||||
logger.log('[NapCat] [Framework] 二维码已被扫描,等待确认...');
|
||||
};
|
||||
|
||||
loginListener.onPasswordLoginFailed = (...args) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录失败:', ...args);
|
||||
};
|
||||
|
||||
loginService.addKernelLoginListener(proxiedListenerOf(loginListener, logger));
|
||||
});
|
||||
// 过早进入会导致addKernelMsgListener等Listener添加失败
|
||||
// await sleep(2500);
|
||||
// 初始化 NapCatFramework
|
||||
const loaderObject = new NapCatFramework(wrapper, session, logger, selfInfo, basicInfoWrapper, pathWrapper, nativePacketHandler, napi2nativeLoader);
|
||||
// 将捕获的 passphrase 设置到 core 上,供 DatabaseApi 使用
|
||||
if (dbPassphrase) {
|
||||
loaderObject.core.dbPassphrase = dbPassphrase;
|
||||
}
|
||||
await loaderObject.core.initCore();
|
||||
|
||||
// 启动WebUi
|
||||
WebUiDataRuntime.setWorkingEnv(NapCatCoreWorkingEnv.Framework);
|
||||
// 登录成功后设置数据路径
|
||||
WebUiDataRuntime.setQQDataPath(loaderObject.core.dataPath);
|
||||
InitWebUi(logger, pathWrapper, logSubscription, statusHelperSubscription).then().catch(e => logger.logError(e));
|
||||
|
||||
// // 测试 DatabaseApi
|
||||
// if (dbPassphrase) {
|
||||
// const dbApi = loaderObject.core.apis.DatabaseApi;
|
||||
// const sqliteOk = await dbApi.isSqliteAvailable();
|
||||
// if (sqliteOk) {
|
||||
// try {
|
||||
// const result = dbApi.readDatabase('nt_msg.db');
|
||||
// if (result) {
|
||||
// logger.log('[NapCat] [Database] nt_msg.db:\n' + dbApi.formatResults([result]));
|
||||
// }
|
||||
// } catch (e) {
|
||||
// logger.logError('[NapCat] [Database] 读取失败:', e);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// 使用 NapCatAdapterManager 统一管理协议适配器
|
||||
const adapterManager = new NapCatAdapterManager(loaderObject.core, loaderObject.context, pathWrapper);
|
||||
await adapterManager.initAdapters();
|
||||
@@ -105,6 +197,164 @@ export async function NCoreInitFramework (
|
||||
}
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
loginService: NodeIKernelLoginService,
|
||||
loginContext: { isLogined: boolean; },
|
||||
logger: LogWrapper
|
||||
) {
|
||||
// 刷新二维码
|
||||
WebUiDataRuntime.setRefreshQRCodeCallback(async () => {
|
||||
loginService.getQRCodePicture();
|
||||
});
|
||||
|
||||
// 快速登录
|
||||
WebUiDataRuntime.setQuickLoginCall(async (uin: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin) {
|
||||
return resolve({ result: false, message: '快速登录失败' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在快速登录', uin);
|
||||
loginService.quickLoginWithUin(uin).then(res => {
|
||||
const success = res.result === '0' && !res.loginErrorInfo?.errMsg;
|
||||
if (!success) {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || `快速登录失败,错误码: ${res.result}`;
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 快速登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('快速登录发生错误');
|
||||
resolve({ result: false, message: '快速登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 密码登录
|
||||
WebUiDataRuntime.setPasswordLoginCall(async (uin: string, passwordMd5: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5) {
|
||||
return resolve({ result: false, message: '密码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在密码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 0,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022008') {
|
||||
const proofWaterUrl = res.loginErrorInfo?.proofWaterUrl || '';
|
||||
resolve({ result: false, message: '需要验证码', needCaptcha: true, proofWaterUrl });
|
||||
} else if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '密码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 密码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('密码登录发生错误');
|
||||
resolve({ result: false, message: '密码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 验证码登录(密码登录需要验证码时的第二步)
|
||||
WebUiDataRuntime.setCaptchaLoginCall(async (uin: string, passwordMd5: string, ticket: string, randstr: string, sid: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !ticket) {
|
||||
return resolve({ result: false, message: '验证码登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在验证码登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 1,
|
||||
newDeviceLoginSig: new Uint8Array(),
|
||||
proofWaterSig: new TextEncoder().encode(ticket),
|
||||
proofWaterRand: new TextEncoder().encode(randstr),
|
||||
proofWaterSid: new TextEncoder().encode(sid),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022010' || res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const newDevicePullQrCodeSig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '新设备需要扫码验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '验证码登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 验证码登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('验证码登录发生错误');
|
||||
resolve({ result: false, message: '验证码登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// 新设备验证登录(密码登录需要新设备验证时的第二步)
|
||||
WebUiDataRuntime.setNewDeviceLoginCall(async (uin: string, passwordMd5: string, newDevicePullQrCodeSig: string) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!uin || !passwordMd5 || !newDevicePullQrCodeSig) {
|
||||
return resolve({ result: false, message: '新设备验证登录失败:参数不完整' });
|
||||
}
|
||||
logger.log('[NapCat] [Framework] 正在新设备验证登录', uin);
|
||||
loginService.passwordLogin({
|
||||
uin,
|
||||
passwordMd5,
|
||||
step: 2,
|
||||
newDeviceLoginSig: new TextEncoder().encode(newDevicePullQrCodeSig),
|
||||
proofWaterSig: new Uint8Array(),
|
||||
proofWaterRand: new Uint8Array(),
|
||||
proofWaterSid: new Uint8Array(),
|
||||
unusualDeviceCheckSig: new Uint8Array(),
|
||||
}).then(res => {
|
||||
if (res.result === '140022011') {
|
||||
const jumpUrl = res.loginErrorInfo?.jumpUrl || '';
|
||||
const sig = res.loginErrorInfo?.newDevicePullQrCodeSig || '';
|
||||
resolve({ result: false, message: '异常设备需要验证', needNewDevice: true, jumpUrl, newDevicePullQrCodeSig: sig });
|
||||
} else if (res.result !== '0') {
|
||||
const errMsg = res.loginErrorInfo?.errMsg || '新设备验证登录失败';
|
||||
WebUiDataRuntime.setQQLoginError(errMsg);
|
||||
resolve({ result: false, message: errMsg });
|
||||
} else {
|
||||
loginContext.isLogined = true;
|
||||
WebUiDataRuntime.setQQLoginStatus(true);
|
||||
WebUiDataRuntime.setQQLoginError('');
|
||||
resolve({ result: true, message: '' });
|
||||
}
|
||||
}).catch((e) => {
|
||||
logger.logError('[NapCat] [Framework] 新设备验证登录异常:', e);
|
||||
WebUiDataRuntime.setQQLoginError('新设备验证登录发生错误');
|
||||
resolve({ result: false, message: '新设备验证登录发生错误' });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class NapCatFramework {
|
||||
public core: NapCatCore;
|
||||
context: InstanceContext;
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
"dependencies": {
|
||||
"napcat-core": "workspace:*",
|
||||
"napcat-common": "workspace:*",
|
||||
"napcat-database": "workspace:*",
|
||||
"napcat-protobuf": "workspace:*",
|
||||
"napcat-adapter": "workspace:*",
|
||||
"napcat-webui-backend": "workspace:*",
|
||||
"napcat-vite": "workspace:*",
|
||||
|
||||
@@ -11,7 +11,7 @@ const external = [
|
||||
'ws',
|
||||
'express',
|
||||
];
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`), 'node:sqlite'].flat();
|
||||
const FrameworkBaseConfigPlugin: PluginOption[] = [
|
||||
autoIncludeTSPlugin({
|
||||
entries: [
|
||||
|
||||
@@ -158,7 +158,7 @@ function bufferToReadStream (buffer: Buffer): ReadStream {
|
||||
read () {
|
||||
this.push(buffer);
|
||||
this.push(null);
|
||||
}
|
||||
},
|
||||
});
|
||||
return readable as unknown as ReadStream;
|
||||
}
|
||||
|
||||
@@ -63,7 +63,6 @@ export class JpegParser implements ImageParser {
|
||||
const bufferSize = buffer.length;
|
||||
const MIN_REQUIRED_BYTES = 10; // SOF段最低字节数
|
||||
|
||||
|
||||
// 从JPEG头部后开始扫描
|
||||
while (offset < bufferSize - MIN_REQUIRED_BYTES) {
|
||||
// 寻找FF标记
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ActionName, BaseCheckResult } from './router';
|
||||
import Ajv, { ErrorObject, ValidateFunction } from 'ajv';
|
||||
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
|
||||
import { NetworkAdapterConfig } from '../config/config';
|
||||
@@ -10,9 +11,9 @@ export const ActionExamples = {
|
||||
errors: [
|
||||
{ code: 1400, description: '请求参数错误或业务逻辑执行失败' },
|
||||
{ code: 1401, description: '权限不足' },
|
||||
{ code: 1404, description: '资源不存在' }
|
||||
]
|
||||
}
|
||||
{ code: 1404, description: '资源不存在' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export class OB11Response {
|
||||
@@ -46,7 +47,7 @@ export abstract class OneBotRequestToolkit {
|
||||
export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
|
||||
core: NapCatCore;
|
||||
private validate?: ValidateFunction<unknown> = undefined;
|
||||
private validate?: TypeCheck<TSchema> = undefined;
|
||||
payloadSchema?: TSchema = undefined;
|
||||
returnSchema?: TSchema = undefined;
|
||||
payloadExample?: unknown = undefined;
|
||||
@@ -64,15 +65,23 @@ export abstract class OneBotAction<PayloadType, ReturnDataType> {
|
||||
}
|
||||
|
||||
protected async check (payload: PayloadType): Promise<BaseCheckResult> {
|
||||
if (this.payloadSchema) {
|
||||
this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema);
|
||||
if (!this.payloadSchema) return { valid: true };
|
||||
try {
|
||||
this.validate = TypeCompiler.Compile(this.payloadSchema);
|
||||
let data = payload;
|
||||
data = Value.Parse(this.payloadSchema, data) as PayloadType;
|
||||
if (typeof payload === 'object' && payload !== null && data !== null) {
|
||||
Object.assign(payload, data);
|
||||
}
|
||||
} catch (e: any) {
|
||||
return { valid: false, message: `Schema compilation error: ${e.message}` };
|
||||
}
|
||||
if (this.validate && !this.validate(payload)) {
|
||||
const errors = this.validate.errors as ErrorObject[];
|
||||
const errorMessages = errors.map(e => `Key: ${e.instancePath.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
if (this.validate && !this.validate.Check(payload)) {
|
||||
const errors = [...this.validate.Errors(payload)];
|
||||
const errorMessages = errors.map(e => `Key: ${e.path.split('/').slice(1).join('.')}, Message: ${e.message}`);
|
||||
return {
|
||||
valid: false,
|
||||
message: errorMessages.join('\n') ?? '未知错误',
|
||||
message: errorMessages.length > 0 ? errorMessages.join('\n') : '未知错误',
|
||||
};
|
||||
}
|
||||
return { valid: true };
|
||||
|
||||
@@ -9,9 +9,9 @@ export const ExtendsActionsExamples = {
|
||||
{
|
||||
type: 'string',
|
||||
characters: [
|
||||
{ character_id: 'id', character_name: 'name', preview_url: 'url' }
|
||||
]
|
||||
}
|
||||
{ character_id: 'id', character_name: 'name', preview_url: 'url' },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
GetClientkey: {
|
||||
|
||||
@@ -27,10 +27,12 @@ export class ClickInlineKeyboardButton extends OneBotAction<PayloadType, ReturnT
|
||||
bot_appid: '1234567890',
|
||||
button_id: 'btn_1',
|
||||
callback_data: '',
|
||||
msg_seq: '10086'
|
||||
msg_seq: '10086',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
return await this.core.apis.MsgApi.clickInlineKeyboardButton({
|
||||
buttonId: payload.button_id,
|
||||
|
||||
@@ -21,11 +21,12 @@ export class CreateCollection extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['扩展接口'];
|
||||
override payloadExample = {
|
||||
rawData: '收藏内容',
|
||||
brief: '收藏标题'
|
||||
brief: '收藏标题',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: 0,
|
||||
errMsg: ''
|
||||
errMsg: '',
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -23,9 +23,11 @@ export class DelGroupAlbumMedia extends OneBotAction<PayloadType, ReturnType> {
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {}
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -19,11 +19,13 @@ export class DoGroupAlbumComment extends OneBotAction<DoGroupAlbumCommentPayload
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
content: '很有意思'
|
||||
content: '很有意思',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {}
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = DoGroupAlbumCommentPayloadSchema;
|
||||
override returnSchema = Type.Any({ description: '评论结果' });
|
||||
|
||||
|
||||
@@ -19,10 +19,11 @@ export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionSummary = '获取自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
count: 10
|
||||
count: 10,
|
||||
};
|
||||
|
||||
override returnExample = [
|
||||
'http://example.com/face1.png'
|
||||
'http://example.com/face1.png',
|
||||
];
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
@@ -30,4 +31,3 @@ export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
|
||||
return ret.emojiInfoList.map(e => e.url);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ const PayloadSchema = Type.Object({
|
||||
emojiId: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
|
||||
emojiType: Type.Union([Type.Number(), Type.String()], { description: '表情类型' }),
|
||||
count: Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' }),
|
||||
cookie: Type.String({ default: '', description: '分页Cookie' })
|
||||
cookie: Type.String({ default: '', description: '分页Cookie' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
@@ -37,22 +37,24 @@ export class FetchEmojiLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
emojiId: '123',
|
||||
emojiType: 1,
|
||||
count: 10,
|
||||
cookie: ''
|
||||
cookie: '',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
emojiLikesList: [
|
||||
{
|
||||
tinyId: '123456',
|
||||
nickName: '测试用户',
|
||||
headUrl: 'http://example.com/avatar.png'
|
||||
}
|
||||
headUrl: 'http://example.com/avatar.png',
|
||||
},
|
||||
],
|
||||
cookie: '',
|
||||
isLastPage: true,
|
||||
isFirstPage: true,
|
||||
result: 0,
|
||||
errMsg: ''
|
||||
errMsg: '',
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -21,32 +21,33 @@ export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
category: '0',
|
||||
count: '50'
|
||||
count: '50',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
errCode: 0,
|
||||
errMsg: "",
|
||||
errMsg: '',
|
||||
collectionSearchList: {
|
||||
collectionItemList: [
|
||||
{
|
||||
cid: "123456",
|
||||
cid: '123456',
|
||||
type: 8,
|
||||
status: 1,
|
||||
author: {
|
||||
type: 2,
|
||||
numId: "123456",
|
||||
strId: "昵称",
|
||||
groupId: "123456",
|
||||
groupName: "群名",
|
||||
uid: "123456"
|
||||
numId: '123456',
|
||||
strId: '昵称',
|
||||
groupId: '123456',
|
||||
groupName: '群名',
|
||||
uid: '123456',
|
||||
},
|
||||
bid: 1,
|
||||
category: 1,
|
||||
createTime: "1769169157000",
|
||||
collectTime: "1769413477691",
|
||||
modifyTime: "1769413477691",
|
||||
sequence: "1769413476735",
|
||||
shareUrl: "",
|
||||
createTime: '1769169157000',
|
||||
collectTime: '1769413477691',
|
||||
modifyTime: '1769413477691',
|
||||
sequence: '1769413476735',
|
||||
shareUrl: '',
|
||||
customGroupId: 0,
|
||||
securityBeat: false,
|
||||
summary: {
|
||||
@@ -58,21 +59,21 @@ export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
|
||||
fileSummary: null,
|
||||
locationSummary: null,
|
||||
richMediaSummary: {
|
||||
title: "",
|
||||
subTitle: "",
|
||||
brief: "text",
|
||||
title: '',
|
||||
subTitle: '',
|
||||
brief: 'text',
|
||||
picList: [],
|
||||
contentType: 1,
|
||||
originalUri: "",
|
||||
publisher: "",
|
||||
richMediaVersion: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
originalUri: '',
|
||||
publisher: '',
|
||||
richMediaVersion: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
hasMore: false,
|
||||
bottomTimeStamp: "1769413477691"
|
||||
}
|
||||
bottomTimeStamp: '1769413477691',
|
||||
},
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -30,16 +30,18 @@ export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['消息扩展'];
|
||||
override payloadExample = {
|
||||
message_id: '12345',
|
||||
emoji_id: '123'
|
||||
emoji_id: '123',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
emoji_like_list: [
|
||||
{
|
||||
user_id: '654321',
|
||||
nick_name: '测试用户'
|
||||
}
|
||||
]
|
||||
nick_name: '测试用户',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
@@ -64,7 +66,7 @@ export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
|
||||
const emojiType = payload.emoji_type ?? (payload.emoji_id.length > 3 ? '2' : '1');
|
||||
const emojiLikeList: Array<{ user_id: string; nick_name: string; }> = [];
|
||||
let cookie = '';
|
||||
let needFetchCount = payload.count == 0 ? 200 : Math.ceil(payload.count / 15);
|
||||
const needFetchCount = payload.count === 0 ? 200 : Math.ceil(payload.count / 15);
|
||||
for (let page = 0; page < needFetchCount; page++) {
|
||||
const res = await this.core.apis.MsgApi.getMsgEmojiLikesList(
|
||||
peer, msg.msgSeq, payload.emoji_id.toString(), emojiType, cookie, 15
|
||||
|
||||
@@ -28,8 +28,8 @@ export class GetFriendWithCategory extends OneBotAction<void, ReturnType> {
|
||||
categoryId: 1,
|
||||
categoryName: '我的好友',
|
||||
categoryMbCount: 1,
|
||||
buddyList: []
|
||||
}
|
||||
buddyList: [],
|
||||
},
|
||||
];
|
||||
|
||||
async _handle () {
|
||||
|
||||
@@ -37,8 +37,8 @@ export default class GetGroupAddRequest extends OneBotAction<void, ReturnType> {
|
||||
group_name: '群名称',
|
||||
checked: false,
|
||||
actor: 0,
|
||||
requester_nick: '请求者'
|
||||
}
|
||||
requester_nick: '请求者',
|
||||
},
|
||||
];
|
||||
|
||||
async _handle (): Promise<ReturnType> {
|
||||
|
||||
@@ -22,11 +22,13 @@ export class GetGroupAlbumMediaList extends OneBotAction<PayloadType, ReturnType
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
media_list: [
|
||||
{ media_id: 'media_id_1', url: 'http://example.com/1.jpg' }
|
||||
]
|
||||
{ media_id: 'media_id_1', url: 'http://example.com/1.jpg' },
|
||||
],
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -16,11 +16,13 @@ export class GetGroupInfoEx extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionSummary = '获取群详细信息 (扩展)';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456'
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
|
||||
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -52,13 +52,15 @@ export class GetMiniAppArk extends GetPacketStatusDepends<PayloadType, ReturnTyp
|
||||
title: '测试标题',
|
||||
desc: '测试描述',
|
||||
picUrl: 'http://example.com/pic.jpg',
|
||||
jumpUrl: 'http://example.com'
|
||||
jumpUrl: 'http://example.com',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
data: {
|
||||
ark: 'ark_content'
|
||||
}
|
||||
ark: 'ark_content',
|
||||
},
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
let reqParam: MiniAppReqParams;
|
||||
const customParams: MiniAppReqCustomParams = {
|
||||
|
||||
@@ -39,8 +39,9 @@ export class GetProfileLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
override payloadExample = {
|
||||
user_id: '123456789',
|
||||
start: 0,
|
||||
count: 10
|
||||
count: 10,
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
uid: 'u_123',
|
||||
time: '1734567890',
|
||||
@@ -48,15 +49,15 @@ export class GetProfileLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
userInfos: [],
|
||||
total_count: 10,
|
||||
last_time: 1734567890,
|
||||
today_count: 5
|
||||
today_count: 5,
|
||||
},
|
||||
voteInfo: {
|
||||
total_count: 100,
|
||||
new_count: 2,
|
||||
new_nearby_count: 0,
|
||||
last_visit_time: 1734567890,
|
||||
userInfos: []
|
||||
}
|
||||
userInfos: [],
|
||||
},
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { NTQQWebApi } from 'napcat-core/apis';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
attach_info: Type.String({ default: '', description: '附加信息(用于分页,从上一次返回结果中获取)' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Array(Type.Any(), { description: '群相册列表' });
|
||||
const ReturnSchema = Type.Object({
|
||||
album_list: Type.Array(Type.Any(), { description: '群相册列表' }),
|
||||
attach_info: Type.String({ description: '分页附加信息,传入下一次请求以获取更多数据' }),
|
||||
has_more: Type.Boolean({ description: '是否有更多数据' }),
|
||||
}, { description: '群相册列表响应' });
|
||||
|
||||
type GetQunAlbumListReturn = Awaited<globalThis.ReturnType<NTQQWebApi['getAlbumListByNTQQ']>>['response']['album_list'];
|
||||
type GetQunAlbumListReturn = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetQunAlbumList extends OneBotAction<PayloadType, GetQunAlbumListReturn> {
|
||||
override actionName = ActionName.GetQunAlbumList;
|
||||
@@ -19,19 +23,31 @@ export class GetQunAlbumList extends OneBotAction<PayloadType, GetQunAlbumListRe
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
attach_info: '',
|
||||
};
|
||||
override returnExample = [
|
||||
{
|
||||
album_id: 'album_1',
|
||||
album_name: '测试相册',
|
||||
cover_url: 'http://example.com/cover.jpg',
|
||||
create_time: 1734567890
|
||||
}
|
||||
];
|
||||
|
||||
override returnExample = {
|
||||
album_list: [
|
||||
{
|
||||
album_id: 'album_1',
|
||||
album_name: '测试相册',
|
||||
cover_url: 'http://example.com/cover.jpg',
|
||||
create_time: 1734567890,
|
||||
},
|
||||
],
|
||||
attach_info: '',
|
||||
has_more: false,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<GetQunAlbumListReturn> {
|
||||
return (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id)).response.album_list;
|
||||
const resp = (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id, payload.attach_info)).response;
|
||||
return {
|
||||
album_list: resp.album_list,
|
||||
attach_info: resp.attach_info,
|
||||
has_more: resp.has_more,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ export class GetRkey extends GetPacketStatusDepends<void, ReturnType> {
|
||||
override payloadExample = {};
|
||||
override returnExample = [
|
||||
{
|
||||
"key": "rkey_value",
|
||||
"expired": 1734567890
|
||||
}
|
||||
key: 'rkey_value',
|
||||
expired: 1734567890,
|
||||
},
|
||||
];
|
||||
|
||||
async _handle () {
|
||||
|
||||
@@ -12,8 +12,9 @@ export class GetRobotUinRange extends OneBotAction<void, ReturnType> {
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {};
|
||||
override returnExample = [
|
||||
{ minUin: '12345678', maxUin: '87654321' }
|
||||
{ minUin: '12345678', maxUin: '87654321' },
|
||||
];
|
||||
|
||||
override payloadSchema = Type.Object({});
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -30,8 +30,8 @@ export class GetUnidirectionalFriendList extends OneBotAction<void, ReturnType>
|
||||
uid: 'u_123',
|
||||
nick_name: '单向好友',
|
||||
age: 20,
|
||||
source: '来源'
|
||||
}
|
||||
source: '来源',
|
||||
},
|
||||
];
|
||||
|
||||
async pack_data (data: string): Promise<Uint8Array> {
|
||||
|
||||
@@ -22,11 +22,12 @@ export class GetUserStatus extends GetPacketStatusDepends<PayloadType, ReturnTyp
|
||||
override actionSummary = '获取用户在线状态';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
user_id: '123456789'
|
||||
user_id: '123456789',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
status: 10,
|
||||
ext_status: 0
|
||||
ext_status: 0,
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -28,9 +28,11 @@ export class MoveGroupFile extends GetPacketStatusDepends<PayloadType, ReturnTyp
|
||||
current_parent_directory: '/current_folder_id',
|
||||
target_parent_directory: '/target_folder_id',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
ok: true
|
||||
ok: true,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -26,11 +26,13 @@ export class RenameGroupFile extends GetPacketStatusDepends<PayloadType, ReturnT
|
||||
group_id: '123456',
|
||||
file_id: '/file_id',
|
||||
current_parent_directory: '/',
|
||||
new_name: 'new_name.jpg'
|
||||
new_name: 'new_name.jpg',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
ok: true
|
||||
ok: true,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -24,8 +24,9 @@ export class SendPacket extends GetPacketStatusDepends<PayloadType, ReturnType>
|
||||
override payloadExample = {
|
||||
cmd: 'Example.Cmd',
|
||||
data: '123456',
|
||||
rsp: true
|
||||
rsp: true,
|
||||
};
|
||||
|
||||
override returnExample = '123456';
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -23,8 +23,9 @@ export class SetDiyOnlineStatus extends OneBotAction<PayloadType, ReturnType> {
|
||||
override payloadExample = {
|
||||
face_id: '123',
|
||||
face_type: '1',
|
||||
wording: '自定义状态'
|
||||
wording: '自定义状态',
|
||||
};
|
||||
|
||||
override returnExample = '';
|
||||
async _handle (payload: PayloadType) {
|
||||
const ret = await this.core.apis.UserApi.setDiySelfOnlineStatus(
|
||||
|
||||
@@ -23,6 +23,7 @@ export default class SetGroupAddOption extends OneBotAction<PayloadType, ReturnT
|
||||
group_id: '123456',
|
||||
add_type: 1,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
@@ -26,9 +26,11 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
|
||||
lloc: 'media_id_1',
|
||||
id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {}
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -22,8 +22,9 @@ export default class SetGroupRemark extends OneBotAction<PayloadType, ReturnType
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
remark: '测试群备注'
|
||||
remark: '测试群备注',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
|
||||
@@ -19,8 +19,9 @@ export default class SetGroupRobotAddOption extends OneBotAction<PayloadType, Re
|
||||
override actionSummary = '设置群机器人加群选项';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456'
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
@@ -19,8 +19,9 @@ export default class SetGroupSearch extends OneBotAction<PayloadType, ReturnType
|
||||
override actionSummary = '设置群搜索选项';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456'
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
@@ -18,8 +18,9 @@ class SetGroupSignBase extends GetPacketStatusDepends<PayloadType, ReturnType> {
|
||||
override actionSummary = '群打卡';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456789'
|
||||
group_id: '123456789',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -22,8 +22,9 @@ export class SetInputStatus extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
user_id: '123456789',
|
||||
event_type: 1
|
||||
event_type: 1,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
|
||||
@@ -24,8 +24,9 @@ export class SetOnlineStatus extends OneBotAction<PayloadType, ReturnType> {
|
||||
override payloadExample = {
|
||||
status: 11,
|
||||
ext_status: 0,
|
||||
battery_status: 100
|
||||
battery_status: 100,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
@@ -252,4 +253,4 @@ const statusText = `
|
||||
"battery_status": 0;
|
||||
}
|
||||
\`\`\`
|
||||
`;
|
||||
`;
|
||||
@@ -15,7 +15,6 @@ const ReturnSchema = Type.Any({ description: '分享结果' });
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class SharePeerBase extends OneBotAction<PayloadType, ReturnType> {
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '分享用户 (Ark)';
|
||||
@@ -23,10 +22,11 @@ export class SharePeerBase extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionTags = ['消息扩展'];
|
||||
override payloadExample = {
|
||||
user_id: '123456',
|
||||
phone_number: ''
|
||||
phone_number: '',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
ark: '...'
|
||||
ark: '...',
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
@@ -58,8 +58,9 @@ export class ShareGroupExBase extends OneBotAction<PayloadTypeGroupEx, ReturnTyp
|
||||
override actionDescription = '获取群分享的 Ark 内容';
|
||||
override actionTags = ['消息扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456'
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = '{"app": "com.tencent.structmsg", ...}';
|
||||
|
||||
async _handle (payload: PayloadTypeGroupEx) {
|
||||
@@ -75,4 +76,4 @@ export class SendGroupArkShare extends ShareGroupExBase {
|
||||
|
||||
export class SendArkShare extends SharePeerBase {
|
||||
override actionName = ActionName.SendArkShare;
|
||||
}
|
||||
}
|
||||
@@ -22,11 +22,13 @@ export class TransGroupFile extends GetPacketStatusDepends<PayloadType, ReturnTy
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
file_id: '/file_id'
|
||||
file_id: '/file_id',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
ok: true
|
||||
ok: true,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export class TranslateEnWordToZn extends OneBotAction<PayloadType, ReturnType> {
|
||||
throw new Error('翻译失败');
|
||||
}
|
||||
return {
|
||||
words: ret.words
|
||||
words: ret.words,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -26,11 +26,13 @@ export class UploadImageToQunAlbum extends OneBotAction<PayloadType, ReturnType>
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
album_name: '相册1',
|
||||
file: '/path/to/image.jpg'
|
||||
file: '/path/to/image.jpg',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: null
|
||||
result: null,
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
|
||||
@@ -26,10 +26,11 @@ export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
files: 'C:\\test.jpg',
|
||||
name: 'test_task'
|
||||
name: 'test_task',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
task_id: 'task_123'
|
||||
task_id: 'task_123',
|
||||
};
|
||||
|
||||
async _handle (payload: CreateFlashTaskPayload) {
|
||||
|
||||
@@ -15,8 +15,9 @@ export class DownloadFileset extends OneBotAction<DownloadFilesetPayload, any> {
|
||||
override actionSummary = '下载文件集';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123'
|
||||
fileset_id: 'set_123',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: DownloadFilesetPayload) {
|
||||
|
||||
@@ -12,15 +12,17 @@ export class GetFilesetId extends OneBotAction<GetFilesetIdPayload, { fileset_id
|
||||
override actionName = ActionName.GetFilesetId;
|
||||
override payloadSchema = GetFilesetIdPayloadSchema;
|
||||
override returnSchema = Type.Object({
|
||||
fileset_id: Type.String({ description: '文件集 ID' })
|
||||
fileset_id: Type.String({ description: '文件集 ID' }),
|
||||
});
|
||||
|
||||
override actionSummary = '获取文件集 ID';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
share_code: '123456'
|
||||
share_code: '123456',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
fileset_id: 'set_123'
|
||||
fileset_id: 'set_123',
|
||||
};
|
||||
|
||||
async _handle (payload: GetFilesetIdPayload) {
|
||||
|
||||
@@ -15,11 +15,12 @@ export class GetFilesetInfo extends OneBotAction<GetFilesetInfoPayload, any> {
|
||||
override actionSummary = '获取文件集信息';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123'
|
||||
fileset_id: 'set_123',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
fileset_id: 'set_123',
|
||||
file_list: []
|
||||
file_list: [],
|
||||
};
|
||||
|
||||
async _handle (payload: GetFilesetInfoPayload) {
|
||||
|
||||
@@ -15,13 +15,14 @@ export class GetFlashFileList extends OneBotAction<GetFlashFileListPayload, any>
|
||||
override actionSummary = '获取闪传文件列表';
|
||||
override actionTags = ['文件扩展'];
|
||||
override payloadExample = {
|
||||
fileset_id: 'set_123'
|
||||
fileset_id: 'set_123',
|
||||
};
|
||||
|
||||
override returnExample = [
|
||||
{
|
||||
file_name: 'test.jpg',
|
||||
size: 1024
|
||||
}
|
||||
size: 1024,
|
||||
},
|
||||
];
|
||||
|
||||
async _handle (payload: GetFlashFileListPayload) {
|
||||
|
||||
Loaded 100 of 257 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user