Compare commits

..
27 Commits
Author SHA1 Message Date
手瓜一十雪 3ba1bd9565 Replace Value.Default/Convert with Value.Parse
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Use Value.Parse from @sinclair/typebox/value instead of the previous Value.Default + Value.Convert sequence across the codebase. Updated config loaders, OneBot action handling, tests and web UI helpers to rely on Value.Parse so schema defaults and coercion are applied consistently and errors surface in a single Parse call. Added two scratch files (scratch.ts, scratch2.ts) to inspect Parse error structure and boolean coercion behavior, and adjusted a test type annotation in test_schema.ts.
2026-03-06 10:23:01 +08:00
手瓜一十雪 8aec6aec1b Use RTT midpoint to adjust Date.now
Measure local time before and after fetching server time and compute offset using the midpoint (compensates for network latency). Round the calculated offset and lower the adjustment threshold from 5000ms to 500ms to avoid applying small corrections. Also rename timing variables for clarity.
2026-03-06 09:57:12 +08:00
手瓜一十雪 36ae7bf923 Replace AJV with TypeBox validation
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Migrate schema validation from AJV to @sinclair/typebox across the monorepo. Key changes:

- Core validation: ConfigBase now uses TypeCompiler/Value (TypeBox) for compile/defaults/coercion and replaces Ajv usage.
- OneBot & Protocol: loadConfig functions and related config loaders updated to use Value.Default/Convert and TypeCompiler.Compile with improved error reporting.
- OneBot action validation: OneBotAction now compiles TypeBox schemas, applies defaults/conversions and returns TypeBox errors.
- Web UI backend: use TypeBox Value/TypeCompiler to fetch and validate defaults for Napcat/Web UI configs.
- Types/scripts: removed AJV type shims and adjusted post-build script to stop special-casing AJV types.
- Dependencies: removed ajv from several package.json files and added/normalized @sinclair/typebox usage; updated pnpm-lock accordingly.
- Tests/tools: added schema validation test utilities and tests (packages/napcat-onebot/test_schema.ts and packages/napcat-test/schema.test.ts) to validate schema compilation, coercion, and defaults.

This change standardizes on TypeBox for runtime schema compilation, default population and type coercion, simplifying validation logic and improving default handling across packages.
2026-03-06 09:46:12 +08:00
手瓜一十雪 4ed4dfd450 Remove no-op voids and add explicit SW return
Remove a pointless `void options.callbackTimeout;` no-op in napcat-rpc client. In the service worker template, add `/* eslint-disable no-undef */` and an explicit `return undefined;` in the cache cleanup callback to make the return value explicit and satisfy linters. In the OneBot debug UI, call `sendRequest(value)` without the leading `void` so the returned promise is not intentionally ignored.
2026-03-05 18:57:30 +08:00
手瓜一十雪 b15d02535e refactor: minor lint and consistency fixes
Apply a collection of small code cleanups across the repo for consistency and lint-safety. Changes include:

- Use strict equality (===) where appropriate (GetEmojiLikes, about page checks).
- Replace Array.map used for side effects with Array.forEach (GetMsg).
- Rename unused catch parameters to underscore-prefixed names to avoid lint warnings (multiple backend/middleware files).
- Replace void with undefined in an actions.call invocation (builtin plugin index).
- Remove an unused loadedCount variable when reading .env (napcat-shell).
- Rename promise resolver parameter to `resolve` for clarity in tests and keep setTimeout usage (rpc.test.ts).
- Strengthen external shims types by changing generic parameter names to _T and update inversify ServiceIdentifier generic param (external-shims.d.ts).
- Simplify post-build script imports and comment out an external-type mapping block; fix a regex character class bug (post-build.mjs).
- Prefix several unused test stub variables with underscore to indicate intentional unused status (test-dist.ts).
- Minor JSX formatting/indentation fixes in password_login component and UI text indentation in system_info.
- Misc: SSE/config and plugin config handlers adjusted to consistent catch parameter naming; update mirror/download error catch variable name.

These edits are non-functional refactors focused on code style, lint compliance and small robustness/clarity improvements.
2026-03-05 18:53:58 +08:00
手瓜一十雪 974528fe7e Apply formatting and minor style fixes across repo
Normalize code style across multiple packages: whitespace cleanup, consistent commas and trailing commas in arrays/enums/objects, fix table markdown lines in CI comment template, ensure newline at EOF, normalize header/object property quoting and spacing, remove stray blank lines and minor non-functional comment tweaks. These are formatting-only changes and small type/annotation spacing adjustments; no functional behavior changes intended.
2026-03-05 18:45:50 +08:00
手瓜一十雪 d2d0b258bc Add per-UIN NapCat config and core UI
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Backend: add per-UIN config support (napcat_{uin}.json) with read/write helpers, handlers (GetUinConfig/SetUinConfig) and router entries; handlers check login status via WebUiDataRuntime and fall back to napcat.json when needed. Frontend: add QQManager methods to get/set per-UIN config, new CoreConfigCard React component for core settings (autoTimeSync, fileLog, consoleLog) and register it in the config page tabs. Types: expose autoTimeSync in NapCatConfig type. Config writes create config directory and merge updates with existing per-UIN config.
2026-03-05 16:35:51 +08:00
手瓜一十雪 2dcba633ba Add configurable automatic time sync
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Add autoTimeSync (default: true) to the Napcat config and honor NAPCAT_DISABLE_TIME_SYNC=1 or autoTimeSync=false to disable automatic time synchronization. When enabled, time sync is attempted via getServerTime with errors logged; warning threshold for significant drift increased from 1s to 5s. Adds informational log when auto time sync is disabled.
2026-03-05 15:38:36 +08:00
手瓜一十雪 53ceb85801 Add server time sync hook and integration
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Introduce helper server-time.ts that preserves the original Date.now and provides hookGlobalDateNow(getServerTimeFn) to compute an offset from a server timestamp and override Date.now when the offset is significant. The function parses a server time string, returns the computed offset, and only patches Date.now if |offset| > 5000ms. Export the helper and call it in NapCatCore startup using session.getMSFService().getServerTime(), logging synchronization results (info for small offsets, warning for >1s) and catching errors. Improves global time consistency with server-provided time.
2026-03-05 15:27:40 +08:00
手瓜一十雪 dbba6b3ffe Add protocol fallback to fetch quoted messages
When existing lookup methods fail to find a referenced/reply message, try a protocol-level fallback using PacketApi. If PacketApi.packetStatus is available, attempt FetchGroupMessage or FetchC2CMessage by sequence, match by contentHead.sequence, and use contentHead.newId as the message id to build reply data. Log warnings on success/not-found and errors on exceptions.
2026-03-05 15:09:58 +08:00
手瓜一十雪 03dd89add0 Disable file logging in main process
Prevent the main process from writing logs to file when running in multi-process mode. base.ts and napcat.ts now disable file logging unless the process is a worker or multi-process mode is disabled (checks NAPCAT_WORKER_PROCESS / NAPCAT_DISABLE_MULTI_PROCESS and ENV.isWorkerProcess / ENV.isMultiProcessDisabled). This reduces duplicate log output and disk I/O by ensuring only worker processes write log files.
2026-03-05 14:56:33 +08:00
手瓜一十雪 7fc70bc5ce Use Type.Omit(..., []) in schema intersections & fix: #1674
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Replace direct schema references inside Type.Intersect with Type.Omit(schema, []) in two places (OB11MessageSchema and OB11MessageImageSchema). This avoids reusing the original schema metadata/$id when intersecting, preventing duplicate-id or type-merging issues with TypeBox/OpenAPI generation.
2026-03-05 14:36:48 +08:00
手瓜一十雪 6758825895 feat: 聊天记录对聊天记录合并转发修复 & fix #1673
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
2026-03-05 13:40:16 +08:00
手瓜一十雪 ae53d27313 Integrate WebUI login flow and callbacks
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Start the WebUI earlier and integrate it with the login process. Initialize WebUI before user login so the UI can control and display login status; set working environment and start InitWebUi asynchronously. Add login listener handlers to update WebUiDataRuntime for QR updates, session failures, login errors, connection events and history. Introduce registerWebUiLoginCallbacks to expose refresh QR, quick login, password/captcha/new-device login flows to the WebUI and update loginContext and UI state accordingly. Also set QQ data path after successful login.
2026-03-05 13:04:57 +08:00
手瓜一十雪 86884b6ba2 Remove onlyBuiltDependencies from pnpm workspace
Remove the onlyBuiltDependencies section from pnpm-workspace.yaml to simplify the workspace configuration. The removed list included '@heroui/shared-utils', '@homebridge/node-pty-prebuilt-multiarch', '@swc/core', esbuild, sharp, ttf2woff2, and unrs-resolver; the file now only declares packages: - packages/*.
2026-03-05 09:22:10 +08:00
手瓜一十雪 776cc8cefd Use NAPCAT_BUILD secret for release
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Switch the release workflow to use the NAPCAT_BUILD secret instead of the default GITHUB_TOKEN. This allows the release job to run with a dedicated token (e.g., with different scopes or credentials) when creating tags, changelogs, and uploading release artifacts.
2026-03-05 09:16:46 +08:00
手瓜一十雪 66542eda26 fix: #1672 2026-03-05 09:15:21 +08:00
手瓜一十雪 34a699c568 Remove Windows one-click package section
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Delete the 'Windows 一键包' section from .github/prompt/default.md, removing the lightweight one-click deployment instructions, reference to NapCat.Shell.Windows.OneKey.zip, and related tutorial notes. Keeps the version header and warning section intact.
2026-03-04 22:22:58 +08:00
手瓜一十雪 2a06688479 Remove SHA512 debug log output
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Remove console.log statements that printed the computed SHA512 hashes for the shell and framework in .github/scripts/publish-release-hash.mjs. This reduces log noise and prevents potentially sensitive hash values from appearing in CI logs while retaining the hash computation logic.
2026-03-04 21:59:00 +08:00
手瓜一十雪 976331af94 Use NAPCAT_BUILD secret in release workflow
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Update .github/workflows/release.yml to set GH_TOKEN from secrets.NAPCAT_BUILD instead of secrets.GH_TOKEN when publishing the release hash. This switches the workflow to use the new/rotated secret name for release publishing.
2026-03-04 21:50:16 +08:00
手瓜一十雪 46b0532f84 Set up gh auth in release workflow
Invoke `gh auth setup-git` in the release GitHub Actions workflow before cloning the hash repo so git is configured to use the GitHub CLI authentication. This prevents authentication issues when running `gh repo clone` and subsequent git operations in CI.
2026-03-04 21:41:17 +08:00
手瓜一十雪 819f76afbf Use gh CLI to clone hash repo in workflow
In the release workflow, replace the token-based git clone URL with the GitHub CLI command. Removed the CLONE_URL variable and now run `gh repo clone NapNeko/napcat-release-hash hash-repo`, avoiding embedding GH_TOKEN in the clone URL and relying on gh authentication for a cleaner, more secure clone.
2026-03-04 21:38:32 +08:00
手瓜一十雪 938074c654 Support selecting account for join key
Add account selection to About page so users can generate the group-join password for different QQ accounts. about.tsx: fetch quick-login list (QQManager.getQQQuickLoginListNew), track selectedUin with useState/useEffect, build account list (including current login as fallback), compute password per selected account (SHA512(hash + uin).substring(0,7)), and render a Select control and updated Snippet/Tooltip UI; also add a binding notice. README and translated docs: add note that the join key is only valid for the latest 100 versions and prompt users to update if it fails.
2026-03-04 21:28:38 +08:00
手瓜一十雪 d16f493136 Publish GitHub release instead of draft
Update the release workflow to publish releases immediately by setting the softprops/action-gh-release step's draft flag to false. Also adjust the step name to "Create Release and Upload Artifacts" to reflect the change so CI will create a published release and upload artifacts instead of leaving a draft.
2026-03-04 21:00:13 +08:00
手瓜一十雪 4c8419d5ab Add release hash script and NapCat file-hash UI
Add a new .github/scripts/publish-release-hash.mjs to compute SHA512 for Shell/Framework napcat.mjs, maintain a release.json (keep last 100 entries) and write it to a separate hash repo. Wire the script into .github/workflows/release.yml to clone NapNeko/napcat-release-hash and publish hashes on release. Backend: expose GET /base/GetNapCatFileHash to compute napcat.mjs SHA512. Frontend: add WebUIManager.GetNapCatFileHash and show a join-password snippet on About page by combining file hash and user UIN (hashed with CryptoJS); update About page links to QQ groups. Update README and localized docs to list community QQ groups. Error handling and basic logging added.
2026-03-04 20:57:53 +08:00
手瓜一十雪 fbba3d5ade fix #1670 2026-03-04 19:27:05 +08:00
水化 cf80c787c3 fix: callbacks cleanup and credential timestamp validation (#1669)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
* fix(rpc): clean callbacks when sending failed

* chore: format

* fix(pty): handle ws message properly

* fix(webui-backend): unify credential timestamp validation

Store credential CreatedTime in seconds and validate expiry using the same unit. Keep backward compatibility for legacy millisecond timestamps.

* chore: format

* Revert "chore: format"

This reverts commit 6f2e9f1b53b55e8f4bf4a747ed7b05a0d6e4dbb4.

* fix: naming

Rename ONE_HOUR_SECONDS to MAX_CREDENTIAL_VALID_SECONDS for clearer intent. Simplify CreatedTime parsing by using Math.floor(Number(...)) and remove the legacy millisecond-to-second conversion branch. Update the time-difference check to use the new constant name.
2026-03-04 19:03:21 +08:00
235 changed files with 2777 additions and 1556 deletions

No files matched your search

-10
View File
@@ -1,16 +1,6 @@
# {VERSION}
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
NapCat.Shell.Windows.OneKey.zip (无头)
启动后可自动化部署一键包,教程参考使用文档安装部分
## 警告
**注意QQ版本推荐使用 40768+ 版本 最低可以使用40768版本**
**默认WebUi密钥为随机密码 控制台查看**
+5 -6
View File
@@ -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');
}
+80
View File
@@ -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}`);
+31 -3
View File
@@ -435,19 +435,19 @@ jobs:
echo "=== generated release note ==="
cat CHANGELOG.md
- name: Create Release Draft and Upload Artifacts
- 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
+15 -1
View File
@@ -14,7 +14,18 @@ English | [简体中文](./docs/README_zh-CN.md) | [繁體中文](./docs/README_
---
## Notice
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested. No public community groups will be established during this period, but NapCat will continue to receive regular updates.
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested.
### Community Groups
You can get the join password directly from the **About** page of the 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)
> 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
@@ -50,6 +61,9 @@ Download the latest version from the [Release](https://github.com/NapNeko/NapCat
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
| 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
+13 -1
View File
@@ -16,7 +16,16 @@ _إطار عمل حديث على جانب البروتوكول مبني على N
---
## إعلان
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com. لن يتم إنشاء مجموعات مجتمع عامة خلال هذه الفترة، لكن NapCat يضمن استمرار التحديثات المنتظمة.
يبحث 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
## مرحباً
@@ -52,6 +61,9 @@ _إطار عمل حديث على جانب البروتوكول مبني على N
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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.
## شكر وتقدير
+15 -1
View File
@@ -14,7 +14,18 @@ _NTQQをベースにした最新のプロトコル側フレームワーク._
---
## お知らせ
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。この期間中、公開コミュニティグループは設立しませんが、NapCat は通常通りの更新を保証します。
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 が必要です。エラーが発生した場合は更新してください。
## ようこそ
@@ -50,6 +61,9 @@ NapCat は現在、新しいメインメンテナーを募集しています。n
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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を提出してください。
## 謝辞
+13 -1
View File
@@ -14,8 +14,17 @@ _NTQQ 기반으로 구현된 최신 프로토콜 사이드 프레임워크._
---
## 공지
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요. 이 기간 동안 공개 커뮤니티 그룹은 만들어지지 않지만, NapCat은 정기적인 업데이트를 보장합니다.
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 프로토콜 구현체입니다
@@ -50,6 +59,9 @@ NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeo
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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을 제출해 주세요.
## 감사의 말
+15 -1
View File
@@ -14,7 +14,18 @@ _Современный фреймворк на стороне протокол
---
## Объявление
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com. В этот период публичные группы сообщества создаваться не будут, но NapCat гарантирует регулярные обновления.
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. Если возникает ошибка, пожалуйста, обновитесь.
## Добро пожаловать
@@ -50,6 +61,9 @@ NapCat в настоящее время ищет нового основного
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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.
## Благодарности
+15 -1
View File
@@ -14,7 +14,18 @@ _基于 NTQQ 实现的现代化协议端框架._
---
## 公告
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com ,在此期不会建立任何公开社区交流群,Napcat会保证此期间的正常更新。
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,如果不符合请更新。
## 欢迎
@@ -50,6 +61,9 @@ NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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。
## 致谢
+15 -1
View File
@@ -14,7 +14,18 @@ _基於 NTQQ 實現的現代化協議端框架._
---
## 公告
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。在此期間不會建立任何公開社群交流群,NapCat 會保證此期間的正常更新。
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,如果錯誤請更新。
## 歡迎
@@ -50,6 +61,9 @@ NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanae
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](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。
## 致謝
-1
View File
@@ -16,7 +16,6 @@
}
},
"dependencies": {
"ajv": "^8.13.0",
"file-type": "^21.0.0"
},
"devDependencies": {
+23 -23
View File
@@ -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);
}
-1
View File
@@ -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);
+1 -1
View File
@@ -21,4 +21,4 @@ export interface ILogWrapper {
logWarn (...args: any[]): void;
logFatal (...args: any[]): void;
logMessage (msg: unknown, selfInfo: unknown): void;
}
}
+8 -12
View File
@@ -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;
}
}
+1 -1
View File
@@ -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
);
}
+1 -1
View File
@@ -114,7 +114,7 @@ export class NTQQOnlineApi {
fileElement: {
fileName: actualFolderName,
filePath: folderPath,
fileSize: "",
fileSize: '',
},
};
+13 -15
View File
@@ -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)
);
}
+3 -3
View File
@@ -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,
+1 -1
View File
@@ -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;
+20 -10
View File
@@ -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) {
+6 -5
View File
@@ -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
);
}
}
@@ -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 -6
View File
@@ -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 {
+18
View File
@@ -38,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';
@@ -50,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,
@@ -173,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];
@@ -53,6 +53,7 @@ export class NodeIKernelLoginListener {
onLoginState (..._args: any[]): any {
}
onLoginRecordUpdate (..._args: any[]): any {
}
}
+7 -8
View File
@@ -16,19 +16,18 @@
}
},
"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:*",
"file-type": "^21.0.0",
"inversify": "^7.10.4",
"json5": "^2.2.3",
"napcat-common": "workspace:*",
"napcat-database": "workspace:*",
"napcat-protobuf": "workspace:*"
"napcat-image-size": "workspace:*",
"napcat-protobuf": "workspace:*",
"reflect-metadata": "^0.2.2",
"winston": "^3.17.0"
},
"devDependencies": {
"@types/node": "^22.0.1"
@@ -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';
@@ -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>;
@@ -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;
-2
View File
@@ -10,7 +10,6 @@ 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;
@@ -299,7 +298,6 @@ export function listTablesFromFile (filePath: string): TableInfo[] {
}
}
export function listTablesFromBuffer (data: Buffer): TableInfo[] {
const tmpPath = path.join(os.tmpdir(), `napcat_db_${Date.now()}_${Math.random().toString(36).slice(2)}.db`);
try {
+2 -2
View File
@@ -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 () {
+219 -11
View File
@@ -46,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);
@@ -60,7 +60,7 @@ 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
@@ -84,16 +84,27 @@ export async function NCoreInitFramework (
// 初始化 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());
});
@@ -104,6 +115,47 @@ 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添加失败
@@ -116,10 +168,8 @@ export async function NCoreInitFramework (
}
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) {
@@ -147,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;
+1 -1
View File
@@ -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标记
+20 -11
View File
@@ -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) {
@@ -17,10 +17,11 @@ export class GetFlashFileUrl extends OneBotAction<GetFlashFileUrlPayload, any> {
override actionSummary = '获取闪传文件链接';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
fileset_id: 'set_123',
};
override returnExample = {
url: 'http://example.com/flash.jpg'
url: 'http://example.com/flash.jpg',
};
async _handle (payload: GetFlashFileUrlPayload) {
@@ -15,8 +15,9 @@ export class GetShareLink extends OneBotAction<GetShareLinkPayload, any> {
override actionSummary = '获取文件分享链接';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
fileset_id: 'set_123',
};
override returnExample = 'http://example.com/share';
async _handle (payload: GetShareLinkPayload) {
@@ -19,10 +19,11 @@ export class SendFlashMsg extends OneBotAction<SendFlashMsgPayload, any> {
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123',
user_id: '123456789'
user_id: '123456789',
};
override returnExample = {
message_id: 123456
message_id: 123456,
};
async _handle (payload: SendFlashMsgPayload) {
@@ -18,8 +18,9 @@ export class CancelOnlineFile extends OneBotAction<CancelOnlineFilePayload, any>
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
msg_id: '123'
msg_id: '123',
};
override returnExample = null;
async _handle (payload: CancelOnlineFilePayload) {
@@ -16,8 +16,9 @@ export class GetOnlineFileMessages extends OneBotAction<GetOnlineFileMessagesPay
override actionSummary = '获取在线文件消息';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789'
user_id: '123456789',
};
override returnExample = [];
async _handle (payload: GetOnlineFileMessagesPayload) {
@@ -20,8 +20,9 @@ export class ReceiveOnlineFile extends OneBotAction<ReceiveOnlineFilePayload, an
override payloadExample = {
user_id: '123456789',
msg_id: '123',
save_path: 'C:\\save'
save_path: 'C:\\save',
};
override returnExample = null;
async _handle (payload: ReceiveOnlineFilePayload) {
@@ -19,8 +19,9 @@ export class RefuseOnlineFile extends OneBotAction<RefuseOnlineFilePayload, any>
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
msg_id: '123'
msg_id: '123',
};
override returnExample = null;
async _handle (payload: RefuseOnlineFilePayload) {
@@ -20,8 +20,9 @@ export class SendOnlineFile extends OneBotAction<SendOnlineFilePayload, any> {
override payloadExample = {
user_id: '123456789',
file_path: 'C:\\path\\to\\file.txt',
file_name: 'test.txt'
file_name: 'test.txt',
};
override returnExample = null;
async _handle (payload: SendOnlineFilePayload) {
@@ -19,8 +19,9 @@ export class SendOnlineFolder extends OneBotAction<SendOnlineFolderPayload, any>
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
folder_path: 'C:\\path\\to\\folder'
folder_path: 'C:\\path\\to\\folder',
};
override returnExample = null;
async _handle (payload: SendOnlineFolderPayload) {
@@ -28,11 +28,12 @@ export class CreateGroupFileFolder extends OneBotAction<PayloadType, ReturnType>
override actionTags = ['Go-CQHTTP'];
override payloadExample = {
group_id: '123456789',
folder_name: '新建文件夹'
folder_name: '新建文件夹',
};
override returnExample = {
result: {},
groupItem: {}
groupItem: {},
};
async _handle (payload: PayloadType) {
@@ -145,7 +145,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<PayloadType, Retur
if (rootMsg) {
// 5. 获取消息内容
const data = await this.core.apis.MsgApi.getMsgHistory(rootMsg.Peer, rootMsg.MsgId, 1);//getMsgsIncludeSelf
const data = await this.core.apis.MsgApi.getMsgHistory(rootMsg.Peer, rootMsg.MsgId, 1);// getMsgsIncludeSelf
if (data && data.result === 0 && data.msgList.length > 0) {
const singleMsg = data.msgList[0];
@@ -3,6 +3,7 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { QuickAction, QuickActionEvent } from '@/napcat-onebot/types';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message';
const SenderSchema = Type.Object({
user_id: Type.String({ description: '用户ID' }),
@@ -16,7 +17,7 @@ const SenderSchema = Type.Object({
// 定义 QuickAction 的详细 Schema
const QuickActionSchema = Type.Object({
reply: Type.Optional(Type.String({ description: '回复内容' })),
reply: Type.Optional(OB11MessageMixTypeSchema),
auto_escape: Type.Optional(Type.Boolean({ description: '是否作为纯文本发送' })),
at_sender: Type.Optional(Type.Boolean({ description: '是否 @ 发送者' })),
delete: Type.Optional(Type.Boolean({ description: '是否撤回该消息' })),
@@ -18,10 +18,11 @@ export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase {
override actionTags = ['Go-CQHTTP'];
override payloadExample = {
group_id: '123456789',
messages: []
messages: [],
};
override returnExample = {
message_id: 123456
message_id: 123456,
};
protected override async check (payload: GoCQHTTPSendForwardMsgPayload) {
@@ -35,11 +36,13 @@ export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase {
override actionTags = ['Go-CQHTTP'];
override payloadExample = {
user_id: '123456789',
messages: []
messages: [],
};
override returnExample = {
message_id: 123456
message_id: 123456,
};
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
return this.base_handle(payload, ContextMode.Private);
}
@@ -51,11 +54,13 @@ export class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase {
override actionTags = ['Go-CQHTTP'];
override payloadExample = {
group_id: '123456789',
messages: []
messages: [],
};
override returnExample = {
message_id: 123456
message_id: 123456,
};
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
return this.base_handle(payload, ContextMode.Group);
}
@@ -25,8 +25,9 @@ export class GetAiRecord extends GetPacketStatusDepends<PayloadType, ReturnType>
override payloadExample = {
character: 'ai_char_1',
group_id: '123456',
text: '你好'
text: '你好',
};
override returnExample = 'http://example.com/ai_voice.silk';
async _handle (payload: PayloadType) {
@@ -26,7 +26,7 @@ export class GetGroupIgnoredNotifies extends OneBotAction<PayloadType, ReturnTyp
override returnExample = {
invited_requests: [],
InvitedRequest: [],
join_requests: []
join_requests: [],
};
async _handle (): Promise<ReturnType> {
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more