Compare commits

...
77 Commits
Author SHA1 Message Date
Copilotandsj817 b253fd82c4 Fix WebUI login page stuck when navigating via token URL (#1835)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* Initial plan

* Fix: set isPasskeyLoading=false when token is in URL to prevent permanently disabled input on login failure

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/fa88593a-3466-40e5-80ff-82c47e1c56e6

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-05-13 10:34:26 +08:00
Ventiの酒 8996b35dd1 fix: enable wss connections and add certificate verification toggle in WebSocket Client (#1823)
* fix: enable wss connections and add certificate verification toggle in WebSocket Client

Previous behavior: the WebSocket Client only supported unencrypted ws:// connections; wss:// URLs were not handled and would fail to connect, providing no option to disable TLS certificate validation for development or self-signed certificates.
Fixed behavior: secure WebSocket connections (wss://) are now fully supported. A verifyCertificate configuration option has been introduced, defaulting to true. When set to false, certificate errors (e.g., self-signed certificates) are ignored, enabling safe local testing while maintaining strict validation by default for production.

* fix: improve wss certificate verification and add tests

Previous behavior: wsOptions used 'any' type without type safety, verifyCertificate was added to napcat-protocol without implementation, and no tests existed for the new config option.

Fixed behavior: wsOptions now uses proper WebSocket.ClientOptions type for compile-time safety, verifyCertificate removed from napcat-protocol (no WebSocket client implementation exists there), and comprehensive tests added to validate config loading and default values.
2026-05-13 10:33:47 +08:00
Bluemangoo 25db6f0835 add ptt to text (#1837) 2026-05-13 10:31:07 +08:00
手瓜一十雪 2c8f9743da Add 9.9.30-48517 appid and napi2native entries
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add mappings for version 9.9.30-48517: update packages/napcat-core/external/appid.json with appid 537352474 and qua "V1_WIN_NQ_9.9.30_48517_GW_B", and update packages/napcat-core/external/napi2native.json with the x64 mapping (send: "0A9B1BC", recv: "1F0324D"). These entries add support for the new 9.9.30-48517 release.
2026-04-26 18:10:40 +08:00
手瓜一十雪 fc26077283 fix: #1793 2026-04-26 17:26:53 +08:00
手瓜一十雪 e9bbc82f37 fix: #1801 2026-04-26 17:21:16 +08:00
时瑾 600f2a4518 fix: replace nclatest proxy with ghfast.top, add dual install commands 2026-04-18 01:29:58 +08:00
时瑾 abf57e688c feat: add proxy prefix to install URL, change TTL to 5 days
- comment.ts: Add PROXY_BASE constant (https://nclatest.znin.net);
  install curl command now uses proxy URL for CN users;
  '24小时' -> '5天'; Docker '7天' -> '5天'
- pr-publish-release.ts: Import PROXY_BASE, use proxy URL in release body,
  '24小时' -> '5天'
2026-04-18 00:31:40 +08:00
时瑾 d92a4cff8d fix: zip absolute path, publish failure comment, pass publish_status
- pr-publish-release.ts: Use resolve() for releaseDir to get absolute path;
  zip command runs with cwd=artifactDir so relative path was resolving wrong
- build-pr.yml: Expose steps.publish.outcome as publish_status job output;
  pass PUBLISH_STATUS env to update-comment-result job
- pr-build-result.ts: Read PUBLISH_STATUS, pass publishFailed to comment
- comment.ts: Show '⚠️ Release 发布失败' section in PR comment when
  publish failed but installInfo is absent
2026-04-18 00:18:46 +08:00
时瑾 e195aee5d2 fix: remove TS overloads incompatible with --experimental-strip-types, fix 204 response, fix retention-days
- lib/github.ts: Remove getEnv overload signatures (Node.js experimental-strip-types
  does not support TS function overloads, causes SyntaxError at parse time)
- lib/github.ts: Handle 204 No Content in request<T> (DELETE returns 204,
  calling response.json() on empty body throws)
- build-pr.yml: retention-days 7->5 (repo max is 5)
2026-04-18 00:08:12 +08:00
时瑾 014a32533d feat: add PR release publish, Docker dispatch and comment system 2026-04-17 23:51:30 +08:00
Airline233andCopilot fa97d15c66 Fix: /get_cookies under the QZone domain returned bkn unexpectedly (#1762)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* Fix: QZone's g_tk(bkn)

Signed-off-by: Airline233 <airline233@gmail.com>

* Add getBknFromPSKey method to webapi

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix variable declaration for BKN in GetCookies

a stupid error...

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix typo in method name for BKN retrieval

Signed-off-by: Airline233 <airline233@gmail.com>

* Fix getBknFromPSKey function call syntax

Signed-off-by: Airline233 <airline233@gmail.com>

* Update packages/napcat-core/apis/webapi.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Airline233 <airline233@gmail.com>

* Update packages/napcat-onebot/action/user/GetCookies.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Airline233 <airline233@gmail.com>

---------

Signed-off-by: Airline233 <airline233@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-16 07:11:31 +08:00
Copilotandsj817 285632f463 fix: preserve user napcat.json config across updates (#1765)
* Initial plan

* fix: prevent o3HookMode from being reset to enabled after NapCat updates

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/98ea8e7d-4ee4-43c1-ac33-2714fba480e3

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* fix: restore o3HookMode default to 1, harden updater against path traversal

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/53b58325-1685-4961-803e-93091dd8b1c4

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-16 07:08:54 +08:00
xboHodx 6d63da4fa0 feat: 新增群待办完成和取消功能 (#1764)
- 添加CompleteGroupTodo和CancelGroupTodo方法
- 重构SetGroupTodo使用BaseGroupTodoAction基类
- 更新相关测试用例和依赖配置

Signed-off-by: xboHodx <2679933924@qq.com>
2026-04-16 07:08:07 +08:00
时瑾 d849188ef2 feat: Add hourly server time synchronization 2026-04-13 19:49:06 +08:00
Copilotandsj817 45966f072e fix(get_msg): return error immediately for recalled messages instead of hanging (#1731)
* Initial plan

* fix: add timeout to getMsgsByMsgId in GetMsg to handle recalled messages

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/15e050cc-734a-4cd5-acb1-69624f6e0978

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* Update GetMsg.ts

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-13 19:30:51 +08:00
c235c92ce9 feat: set_group_ban fails when admin attempts to ban another admin (#1742)
* Initial plan

* feat: set_group_ban returns failed when admin tries to ban another admin

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/5c497921-6acb-41fd-a8d3-ad84f59a0eb8

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

* Update SetGroupBan.ts

* Update packages/napcat-onebot/action/group/SetGroupBan.ts

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: 时瑾 <shijinn520@gmail.com>

---------

Signed-off-by: 时瑾 <shijinn520@gmail.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
Co-authored-by: 时瑾 <shijinn520@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-13 19:26:57 +08:00
Copilotandsj817 a62c9298ac fix: accept NAPCAT_DISABLE_MULTIPROCESSING as alias for NAPCAT_DISABLE_MULTI_PROCESS (#1757)
* Initial plan

* fix: accept NAPCAT_DISABLE_MULTIPROCESSING as alias for NAPCAT_DISABLE_MULTI_PROCESS

Agent-Logs-Url: https://github.com/NapNeko/NapCatQQ/sessions/1f67b134-2798-41ad-9d26-b9b82f5adb7d

Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: sj817 <74231782+sj817@users.noreply.github.com>
2026-04-13 19:18:57 +08:00
手瓜一十雪 c5bc48da1f Remove NAPCAT_BUILD token from workflow
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Remove the explicit `token: ${{ secrets.NAPCAT_BUILD }}` line from the release-publish GitHub Actions workflow. This stops passing the custom NAPCAT_BUILD secret to the release step, allowing the action to use the default authentication mechanism or another configured token and reducing exposure of the custom secret.
2026-04-05 20:31:17 +08:00
006lp 4edb3385e4 feat(appid,napi2native,packet): add early support for QQ client version 47354 (#1743)
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
* feat(appid): add support for QQ client versions 47354

Add appid and qua configurations for new QQ client versions:

QQ 3.2.27-47354-x64 (Linux)

QQ 9.9.29-47354-x64 (Windows)

QQ 6.9.93-47354-arm64 (macOS)

* Update napi2native version keys to 47354 (win-x64,linux-x64/arm64)

* Update napi2native version keys to 47354 (mac-arm64)

* Update napi2native version keys to 47354 (mac-x64)

* feat(packet): add support for QQ client version 47354
2026-04-05 20:29:06 +08:00
手瓜一十雪 10f961c552 Update OPENAI_MODEL in release workflow
Change the OPENAI_MODEL environment variable in .github/workflows/release-publish.yml from "openrouter/hunter-alpha" to "z-ai/glm-4.5-air:free" so the release-publish job uses the new model endpoint for OpenAI API calls. No other workflow changes.
2026-03-22 15:19:40 +08:00
手瓜一十雪 0baf800d21 Add mappings for 46928 and 9.9.28 builds
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Update packages/napcat-core/external/napi2native.json and packet.json to include send/recv offsets for 3.2.26-46928 (x64 and arm64) and 9.9.28-46928-x64. Arm64 entries reuse the same offsets as 3.2.26-46494-arm64; new x64 offsets were added for both files.
2026-03-22 12:25:58 +08:00
Rinandrin 5c0fac7de6 feat: 群公告/精华等接口引入 psKey 缓存 (#1716)
* fix: 群公告/精华等接口的 psKey 缓存优化

- 在 NTQQGroupApi 中新增 _qunPskeyCache 缓存字段(TTL 4分钟)
- 新增 getQunPskey() 私有方法,统一管理 qun.qq.com 域名的 psKey 获取
- fetchGroupEssenceList、deleteGroupBulletin、uploadGroupBulletinPic、publishGroupBulletin
  共 4 处调用改为共享缓存,避免每次请求都独立拉取 psKey,减少 HTTP 请求次数
- 缓存过期后自动刷新,无需手动管理

* fix: 改用滑动 TTL + 惰性删除管理 psKey 缓存

- TTL 从硬编码 4 分钟改为 60 秒滑动窗口
- 每次访问顺延过期时间(滑动 TTL),避免频繁刷新
- 过期后惰性删除,下次访问时直接覆盖,无主动清理开销
- 回应 reviewer 建议:滑动窗口比固定 TTL 更适合偶发调用场景

---------

Co-authored-by: rin <rin@rin.red>
2026-03-22 12:19:39 +08:00
手瓜一十雪 c7109e20ad Use GITHUB_TOKEN for downstream trigger
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Replace secrets.NAPCAT_BUILD with the built-in secrets.GITHUB_TOKEN in the release-publish workflow to authenticate triggering downstream release workflows. This removes dependency on a custom secret and uses the repo-scoped Actions token for simpler, more secure automation.
2026-03-14 12:51:00 +08:00
手瓜一十雪 d61433f2a4 Update OPENAI_MODEL in release workflow
Update the OPENAI_MODEL env var in .github/workflows/release-publish.yml from "stepfun/step-3.5-flash:free" to "openrouter/hunter-alpha" so the release publish job uses the new model for API calls. No other workflow changes.
2026-03-13 22:58:03 +08:00
手瓜一十雪 0ae05ccb8d Use default duration if getDuration fails
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Add a fallback for video duration by including this.getDuration(videoPath).catch(() => 60) in the Promise.all alongside fileTypeFromFile. This prevents Promise.all from rejecting when duration retrieval fails and supplies a sensible default (60s) for downstream processing (e.g., thumbnail generation).
2026-03-13 19:48:31 +08:00
手瓜一十雪 973ccaebed Throw on invalid ffprobe duration, remove prefetch
Remove prefetching of video duration from the initial Promise.all and change getDuration to stop swallowing errors: it now throws when ffprobe returns a non-numeric duration (including the raw stdout in the error) instead of returning a default 60s. This prevents silently masking ffprobe failures — callers should handle or catch errors from getDuration.
2026-03-13 19:48:14 +08:00
手瓜一十雪 59bd457a97 Refactor GitHub Actions workflows
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
Rework CI/CD by replacing and reorganizing GitHub Actions workflows. Added build-ci.yml (typecheck/test + matrix builds), release-downstream.yml (dispatch downstream releases), and release-tag.yml (tag validation + trigger). Renamed pr-build.yml → build-pr.yml and release.yml → release-publish.yml to use input-driven release flows. Removed deprecated workflows (auto-release.yml, build.yml) and deleted locale README files under docs (README_ar/ja/ko/ru/zh-CN/zh-TW). Changes include artifact matrix builds, caching and optimized Windows assembly steps, OpenAPI schema publishing to NapCatDocs, and explicit downstream workflow dispatching on release.
2026-03-13 19:22:00 +08:00
手瓜一十雪 d70e06a4f5 Update napi2native version keys to 46494 & fix #1699
Replace three entries in packages/napcat-core/external/napi2native.json that used the '-46949' suffix with '-46494' for versions 9.9.28-x64 and 3.2.26 (x64 and arm64). send/recv hashes are unchanged; this corrects the version/build identifiers in the mapping.
2026-03-13 18:12:50 +08:00
时瑾 e6f6468377 Revert "fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)" (#1701)
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
This reverts commit deae7fd467.
2026-03-13 15:26:53 +08:00
MliKiowa 9d5f0ee604 Revise README with new feature details and groups
Updated README to include new features and community group information.

Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-03-12 23:19:40 +08:00
手瓜一十雪 07d4d80ab7 Add isLocal flag to uriToLocalFile and use it
Expose an isLocal boolean from uriToLocalFile to indicate user-owned files vs temporary downloads/decodes, and update callers to avoid deleting or cleaning up user local files. Update OneBot file APIs to accept the isLocal hint (including createValidSendFileElement/createValidSendPicElement/createValidSendVideoElement) and adjust temp-file handling for videos: local files are copied into the NapCat temp dir with a random UUID filename to avoid polluting user directories, while temporary files get an added extension in-place. Also adjust deleteAfterSentFiles usage, image/video thumb handling, and numeric parsing fallbacks for element fileSize to be more robust. Minor imports (randomUUID) and related callsites were updated accordingly.
2026-03-12 15:36:44 +08:00
手瓜一十雪 7a974d38d4 Use element.fileSize fields to calc totalSize
Remove filesystem stat calls and the node:fs/promises import; replace the async size calculation with a synchronous reduce that sums parseInt(fileSize) from each send element (falls back to 0 on parse failure). This avoids runtime I/O, simplifies the logic, and still provides a totalSize used to compute message timeout.
2026-03-12 15:07:44 +08:00
手瓜一十雪 e9b74138d1 Add configurable timeout calculation for transfers
Introduce timeout configuration and automatic timeout estimation for uploads/downloads. Added TimeoutConfig to OneBot config with baseTimeout, upload/downloadSpeedKBps and maxTimeout, plus calculateTimeout and capTimeout helpers. Applied estimation to FileApi.downloadFileById calls (GetFile, BaseDownloadStream) and to message sending (OneBotMsgApi) to compute timeouts from total payload size; sendMsg now accepts an optional timeout override which is capped by maxTimeout. Updated SendMsg payload schema to allow a custom timeout, and updated web UI store, types and config form to expose timeout settings and defaults.
2026-03-12 15:01:34 +08:00
手瓜一十雪 df0795f2c5 Update GitHub Actions to newer versions
Upgrade workflow action versions across .github/workflows: actions/checkout@v4 -> @v5, actions/setup-node@v4 -> @v6, actions/upload-artifact@v4 -> @v6, and actions/download-artifact@v4 -> @v7. Changes touch auto-release.yml, build.yml, pr-build.yml, and release.yml to keep CI tooling current and compatible with newer runner features; also add a missing newline at end of auto-release.yml.
2026-03-12 14:04:00 +08:00
手瓜一十雪 85b56e52ac fix: #1697
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-12 13:51:54 +08:00
时瑾 77c89d0923 lint: eslint
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-12 09:09:26 +08:00
时瑾 58b36cd331 fix: 优化Passkey在非安全场景下无法使用的提示 #1680 2026-03-12 09:08:47 +08:00
吴天一 deae7fd467 fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)
* fix: make defaulted request fields optional

* fix: align onebot schemas with runtime behavior

* fix: tighten schema and unsupported action metadata

* fix: reject empty forward reference ids

* fix: update GoCQHTTPSendForwardMsg to handle messages correctly and adjust payload schema

* fix: refactor message handling in GoCQHTTPSendForwardMsg and add test for message normalization

* fix: update compatibility actions to return appropriate responses and align schemas with runtime behavior

* fix: ensure payload properties are non-null with default values in action handlers

* fix: update StreamStatus comments for clarity and enforce nickname as required in message schema

* fix: integrate sleep function in GetOnlineClient and update tests to verify API call

* fix: add production test checklist for OneBot schema alignment and message handling

* fix: remove outdated production test checklist for OneBot schema alignment
2026-03-12 01:54:33 +08:00
吴天一 8b2207e109 fix: make album attach_info optional (#1690) 2026-03-09 20:01:43 +08:00
手瓜一十雪 f3b76e8b3a Add new version mappings in external JSON
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 send/recv offsets for several new builds to packages/napcat-core/external/napi2native.json and packages/napcat-core/external/packet.json. Entries added: 9.9.27-46949-x64 and 3.2.26-46949-(x64, arm64) in napi2native.json; 3.2.26-46494-(x64, arm64) and 9.9.28-46494-x64 in packet.json. These register offsets for newly encountered builds.
2026-03-08 19:39:27 +08:00
006lp 466d9a3c4f feat(appid): add support for QQ client versions 46494 (#1681)
Add appid and qua configurations for new QQ client versions:
- QQ 3.2.26-46494 (Linux)
- QQ 9.9.28-46494 (Windows)
- QQ 6.9.90-46494 (macOS)
2026-03-08 19:28:28 +08:00
MliKiowa 4af49c5761 chore: remove manifest.json from
Removed manifest.json from the copy targets in the Vite configuration.

Signed-off-by: MliKiowa <nanaeonn@outlook.com>
2026-03-06 22:47:23 +08:00
手瓜一十雪 442ad4f9a3 feat: 正式中断插件注入启动模式 2026-03-06 22:33:27 +08:00
手瓜一十雪 7ee2f1c40d Fix imports and formatting in packages
Small cleanup across multiple packages: adjust TypeBox imports (add TSchema) and reorder imports in napcat-core/helper/config.ts; normalize indentation and type formatting in napcat-protobuf/NapProto.ts; add missing trailing commas and minor object formatting fixes in tests (packages/napcat-test/schema.test.ts); remove an extra blank line in external-shims.d.ts; and remove an unnecessary blank line in post-build.mjs. These are whitespace/formatting and minor import fixes to satisfy linting and type checks.
2026-03-06 10:54:31 +08:00
手瓜一十雪 7380665cc2 Notify log subscription only when logger exists
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
Move logSubscription.notify into the branch that calls this.logger.log and remove the previous external call. This ensures the subscription is notified only when the configured logger is used, avoiding redundant or spurious notifications.
2026-03-06 10:48:03 +08:00
手瓜一十雪 2c57faf117 Disable file logs by default; lazy-init transport
Set file logging off by default and defer creation of the File transport until file logging is enabled. Store logPath and fileLogLevel (with fileTransportAdded flag) so the file transport can be added later with the correct filename and level. Remove the eager File transport from the constructor, update setFileAndConsoleLogLevel to persist fileLogLevel, and add the transport in setFileLogEnabled(true). Improve _log to only format messages when needed and notify subscribers once. Replace some direct logger.* calls with wrapper methods for consistent handling when deleting/reading old log files.
2026-03-06 10:47:09 +08:00
手瓜一十雪 8b0d186625 Remove napcat-onebot test_schema.ts
Delete packages/napcat-onebot/test_schema.ts — a standalone script that compiled and validated OB11 TypeBox schemas and performed a sample validation. This file appeared to be a local test/diagnostic harness and was removed as part of cleanup to avoid keeping ad-hoc test scripts in the package source.
2026-03-06 10:32:48 +08:00
手瓜一十雪 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
手瓜一十雪 7b58681b2b feat: 修复database disk image is malforme
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-04 15:33:55 +08:00
手瓜一十雪 7c2eacf0dc Switch release workflow to OpenAI endpoint
Update .github/workflows/release.yml to use the OpenRouter/OpenAI public endpoint and standardized env names. Replaced custom API URL and model with OPENAI_API_URL=https://openrouter.ai/api/v1/chat/completions and OPENAI_MODEL="stepfun/step-3.5-flash:free", renamed variables (OPENROUTER_* → OPENAI_*), adjusted the job step name and log messages, and updated the curl request and response handling to use the new env vars. Kept existing behavior for generating release notes and the fallback to the default template when the LLM output is empty.
2026-03-04 12:01:11 +08:00
294 changed files with 4792 additions and 2837 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密钥为随机密码 控制台查看**
+192 -6
View File
@@ -3,6 +3,16 @@
*/
export const COMMENT_MARKER = '<!-- napcat-pr-build -->';
export const DOCKER_COMMENT_MARKER = '<!-- napcat-pr-docker -->';
// 默认代理前缀(加速中国大陆访问 GitHub Release)
// 格式:https://ghfast.top/{full-github-url}
export const PROXY_BASE = 'https://gh.llkk.cc';
/** 将 GitHub 直链转换为 ghfast.top 加速链接 */
export function toProxyUrl (directUrl: string): string {
return `${PROXY_BASE}/${directUrl}`;
}
export type BuildStatus = 'success' | 'failure' | 'cancelled' | 'pending' | 'unknown';
@@ -84,8 +94,8 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
'',
'## 📋 构建信息',
'',
`| 项目 | 值 |`,
`| :--- | :--- |`,
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🕐 开始时间 | ${time} |`,
'',
@@ -105,12 +115,19 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
// ============== 构建结果评论 ==============
export interface InstallInfo {
installUrl: string;
releaseUrl: string;
}
export function generateResultComment (
targets: BuildTarget[],
prSha: string,
runId: string,
repository: string,
version?: string
version?: string,
installInfo?: InstallInfo,
publishFailed?: boolean
): string {
const runUrl = `https://github.com/${repository}/actions/runs/${runId}`;
const shortSha = formatSha(prSha);
@@ -165,21 +182,56 @@ export function generateResultComment (
'',
'## 📋 构建信息',
'',
`| 项目 | 值 |`,
`| :--- | :--- |`,
'| 项目 | 值 |',
'| :--- | :--- |',
...(version ? [`| 🏷️ 版本号 | \`${version}\` |`] : []),
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 构建日志 | [查看详情](${runUrl}) |`,
`| 🕐 完成时间 | ${time} |`,
];
// 添加快速安装命令
if (installInfo) {
const directUrl = installInfo.installUrl;
const proxyInstallUrl = toProxyUrl(directUrl);
lines.push(
'',
'---',
'',
'## 🚀 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
`> 📦 [查看 Release 页面](${installInfo.releaseUrl})`,
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。'
);
} else if (publishFailed) {
lines.push(
'',
'---',
'',
'## ⚠️ Release 发布失败',
'',
'> ❌ PR Release 发布过程中出现错误,无法提供快速安装命令。',
`> 🔗 [查看构建日志](${runUrl}) 了解详情。`
);
}
// 添加错误详情
const failedTargets = targets.filter(t => t.status === 'failure' && t.error);
if (failedTargets.length > 0) {
lines.push('', '---', '', '## ⚠️ 错误详情', '');
for (const target of failedTargets) {
lines.push(
`<details>`,
'<details>',
`<summary>🔴 <b>${target.name}</b> 构建错误</summary>`,
'',
'```',
@@ -229,3 +281,137 @@ export function generateResultComment (
return lines.join('\n');
}
// ============== Docker 构建评论 ==============
export function generateDockerBuildingComment (prNumber: string, prSha: string): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
'# 🐳 Docker 测试镜像构建中',
'',
'![Building](https://img.shields.io/badge/Docker-构建中-yellow?style=for-the-badge&logo=docker&logoColor=white)',
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 触发时间 | ${time} |`,
'',
'---',
'',
'<div align="center">',
'',
'> ⏳ **Docker 镜像正在构建中,请稍候...**',
'>',
'> 构建完成后将自动更新此评论',
'',
'</div>',
];
return lines.join('\n');
}
export function generateDockerResultComment (
prNumber: string,
prSha: string,
success: boolean,
dockerImage?: string,
error?: string
): string {
const time = getTimeString();
const shortSha = formatSha(prSha);
const statusBadge = success
? '![Success](https://img.shields.io/badge/Docker-构建成功-success?style=for-the-badge&logo=docker&logoColor=white)'
: '![Failed](https://img.shields.io/badge/Docker-构建失败-critical?style=for-the-badge&logo=docker&logoColor=white)';
const headerTitle = success ? '# ✅ Docker 测试镜像就绪' : '# ❌ Docker 测试镜像构建失败';
const lines: string[] = [
DOCKER_COMMENT_MARKER,
'',
'<div align="center">',
'',
headerTitle,
'',
statusBadge,
'',
'</div>',
'',
'---',
'',
'## 📋 构建信息',
'',
'| 项目 | 值 |',
'| :--- | :--- |',
`| 📝 提交 | \`${shortSha}\` |`,
`| 🔗 PR | #${prNumber} |`,
`| 🕐 完成时间 | ${time} |`,
];
if (success && dockerImage) {
lines.push(
'',
'---',
'',
'## 🚀 快速使用',
'',
'```bash',
`docker pull ${dockerImage}`,
'```',
'',
'> ⚠️ 此为 PR 测试镜像,保留 5 天后自动清理。'
);
}
if (!success && error) {
lines.push(
'',
'---',
'',
'<details>',
'<summary>🔴 <b>错误详情</b></summary>',
'',
'```',
escapeCodeBlock(error),
'```',
'',
'</details>'
);
}
lines.push('', '---', '');
if (success) {
lines.push(
'<div align="center">',
'',
'> 🎉 **Docker 测试镜像已就绪!**',
'>',
'> 使用上方命令拉取镜像进行测试',
'',
'</div>'
);
} else {
lines.push(
'<div align="center">',
'',
'> ⚠️ **Docker 镜像构建失败**',
'>',
'> 请检查错误详情',
'',
'</div>'
);
}
return lines.join('\n');
}
+112 -2
View File
@@ -31,6 +31,21 @@ export interface Artifact {
archive_download_url: string;
}
export interface Release {
id: number;
tag_name: string;
name: string;
upload_url: string;
html_url: string;
created_at: string;
}
export interface ReleaseAsset {
id: number;
name: string;
browser_download_url: string;
}
// ============== GitHub API Client ==========================
export class GitHubAPI {
@@ -56,6 +71,11 @@ export class GitHubAPI {
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
// 204 No Content(DELETE 等)不解析 body
if (response.status === 204) {
return undefined as T;
}
return response.json() as Promise<T>;
}
@@ -150,6 +170,97 @@ export class GitHubAPI {
console.log('✓ Created new comment');
}
}
// ============== Release API ==============
async getReleaseByTag (owner: string, repo: string, tag: string): Promise<Release | null> {
try {
return await this.request<Release>(`/repos/${owner}/${repo}/releases/tags/${tag}`);
} catch {
return null;
}
}
async deleteRelease (owner: string, repo: string, releaseId: number): Promise<void> {
await this.request(`/repos/${owner}/${repo}/releases/${releaseId}`, { method: 'DELETE' });
}
async deleteRef (owner: string, repo: string, ref: string): Promise<void> {
try {
await this.request(`/repos/${owner}/${repo}/git/refs/${ref}`, { method: 'DELETE' });
} catch {
// ref may not exist, ignore
}
}
async createRelease (
owner: string,
repo: string,
tag: string,
name: string,
body: string,
prerelease = true
): Promise<Release> {
return this.request<Release>(`/repos/${owner}/${repo}/releases`, {
method: 'POST',
body: JSON.stringify({ tag_name: tag, name, body, prerelease }),
headers: { 'Content-Type': 'application/json' },
});
}
async uploadReleaseAsset (
uploadUrl: string,
fileName: string,
data: Buffer,
contentType = 'application/octet-stream'
): Promise<ReleaseAsset> {
const url = uploadUrl.replace(/\{[^}]*\}/g, '') + `?name=${encodeURIComponent(fileName)}`;
const response = await fetch(url, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'Content-Type': contentType,
'X-GitHub-Api-Version': '2022-11-28',
},
body: data,
});
if (!response.ok) {
throw new Error(`Upload ${fileName} failed: ${response.status} ${response.statusText}`);
}
return response.json() as Promise<ReleaseAsset>;
}
// ============== Dispatch API ==============
async repositoryDispatch (
owner: string,
repo: string,
eventType: string,
clientPayload: Record<string, string>
): Promise<void> {
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/dispatches`, {
method: 'POST',
headers: {
Authorization: `Bearer ${this.token}`,
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28',
'Content-Type': 'application/json',
},
body: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
});
if (!response.ok && response.status !== 204) {
throw new Error(`Dispatch failed: ${response.status} ${response.statusText}`);
}
}
// ============== Release Cleanup API ==============
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
return this.request<Release[]>(
`/repos/${owner}/${repo}/releases?per_page=${perPage}&page=${page}`
);
}
}
// ============== Output 工具 ==============
@@ -172,8 +283,7 @@ export function setMultilineOutput (name: string, value: string): void {
// ============== 环境变量工具 ==============
export function getEnv (name: string, required: true): string;
export function getEnv (name: string, required?: false): string | undefined;
// Note: 不使用函数重载——Node.js --experimental-strip-types 不支持 TS overload signatures
export function getEnv (name: string, required = false): string | undefined {
const value = process.env[name];
if (required && !value) {
+19 -2
View File
@@ -11,11 +11,13 @@
* - FRAMEWORK_ERROR: Framework 构建错误信息
* - SHELL_STATUS: Shell 构建状态
* - SHELL_ERROR: Shell 构建错误信息
* - INSTALL_URL: PR Release 安装脚本 URL (可选)
* - RELEASE_URL: PR Release 页面 URL (可选)
*/
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
import { generateResultComment, COMMENT_MARKER } from './lib/comment.ts';
import type { BuildTarget, BuildStatus } from './lib/comment.ts';
import type { BuildTarget, BuildStatus, InstallInfo } from './lib/comment.ts';
function parseStatus (value: string | undefined): BuildStatus {
if (value === 'success' || value === 'failure' || value === 'cancelled') {
@@ -46,6 +48,21 @@ async function main (): Promise<void> {
console.log(`Framework: ${frameworkStatus}${frameworkError ? ` (${frameworkError})` : ''}`);
console.log(`Shell: ${shellStatus}${shellError ? ` (${shellError})` : ''}\n`);
// PR Release 信息(由 publish-pr-release job 传入)
const installUrl = getEnv('INSTALL_URL');
const releaseUrl = getEnv('RELEASE_URL');
const publishStatus = getEnv('PUBLISH_STATUS'); // 'success' | 'failure' | 'skipped' | ''
const installInfo: InstallInfo | undefined =
installUrl && releaseUrl ? { installUrl, releaseUrl } : undefined;
const publishFailed = publishStatus === 'failure';
if (installInfo) {
console.log(`Install URL: ${installUrl}`);
console.log(`Release URL: ${releaseUrl}\n`);
} else if (publishFailed) {
console.log('Publish status: FAILED\n');
}
const github = new GitHubAPI(token);
const repository = `${owner}/${repo}`;
@@ -79,7 +96,7 @@ async function main (): Promise<void> {
},
];
const comment = generateResultComment(targets, prSha, runId, repository, version);
const comment = generateResultComment(targets, prSha, runId, repository, version, installInfo, publishFailed);
await github.createOrUpdateComment(owner, repo, prNumber, comment, COMMENT_MARKER);
}
+69
View File
@@ -0,0 +1,69 @@
/**
* PR Build - 触发 NapCat-Docker 仓库构建 PR 测试镜像
*
* 功能:
* 1. 在 PR 中创建 Docker 构建中评论
* 2. 触发 NapCat-Docker 仓库的 repository_dispatch 事件
*
* 环境变量:
* DISPATCH_PAT - 具备目标仓库 dispatch 权限的 PAT
* GITHUB_TOKEN - GitHub API Token (用于写 PR 评论)
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* PR_HEAD_REPO - PR 源仓库 (owner/repo)
* SOURCE_REPO - 当前仓库 (默认 NapNeko/NapCatQQ)
* RELEASE_REPO - PR release 仓库 (默认 NapNeko/napcat-pr-release)
* TARGET_REPO - Docker 仓库 (默认 NapNeko/NapCat-Docker)
*/
import { GitHubAPI, getEnv } from './lib/github.ts';
import { generateDockerBuildingComment, DOCKER_COMMENT_MARKER } from './lib/comment.ts';
async function main (): Promise<void> {
console.log('🐳 Dispatching Docker build\n');
const token = getEnv('DISPATCH_PAT', true);
const githubToken = getEnv('GITHUB_TOKEN', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const prHeadRepo = getEnv('PR_HEAD_REPO') || '';
const sourceRepo = getEnv('SOURCE_REPO') || 'NapNeko/NapCatQQ';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const targetRepo = getEnv('TARGET_REPO') || 'NapNeko/NapCat-Docker';
const [targetOwner, targetRepoName] = targetRepo.split('/');
const [sourceOwner, sourceRepoName] = sourceRepo.split('/');
const shortSha = prSha.substring(0, 7);
console.log(` PR: #${prNumber}`);
console.log(` SHA: ${shortSha}`);
console.log(` Target: ${targetRepo}`);
console.log(` Release: ${releaseRepo}\n`);
// 在 PR 中创建 Docker 构建中评论
console.log('💬 Creating Docker building comment...');
const prGithub = new GitHubAPI(githubToken);
const dockerComment = generateDockerBuildingComment(prNumber, prSha);
await prGithub.createOrUpdateComment(
sourceOwner, sourceRepoName, parseInt(prNumber, 10), dockerComment, DOCKER_COMMENT_MARKER
);
// 触发 Docker 仓库构建
const github = new GitHubAPI(token);
await github.repositoryDispatch(targetOwner, targetRepoName, 'napcatqq-pr-build', {
pr_number: prNumber,
pr_sha: prSha,
pr_short_sha: shortSha,
pr_head_repo: prHeadRepo,
source_repo: sourceRepo,
release_repo: releaseRepo,
});
console.log('✅ Dispatch succeeded');
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+173
View File
@@ -0,0 +1,173 @@
/**
* PR Build - 发布构建产物到 napcat-pr-release 仓库
*
* 功能:
* 1. 将 CI 构建产物(Framework / Shell)打包为 zip
* 2. 从 NapCat-Installer 仓库拉取 install.sh 并替换下载链接
* 3. 发布到 napcat-pr-release 仓库的 GitHub Release
*
* 环境变量:
* RELEASE_PAT - 具备目标仓库 release 写权限的 PAT
* PR_NUMBER - PR 编号
* PR_SHA - PR HEAD 提交 SHA
* NAPCAT_VERSION - 构建版本号
* ARTIFACTS_DIR - 构建产物目录 (默认 ./artifacts)
* RELEASE_REPO - 发布仓库 (默认 NapNeko/napcat-pr-release)
* INSTALLER_REPO - 安装脚本仓库 (默认 NapNeko/NapCat-Installer)
* INSTALLER_BRANCH - 安装脚本分支 (默认 main)
*/
import { execSync } from 'node:child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
import { join, basename, resolve } from 'node:path';
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
import { toProxyUrl } from './lib/comment.ts';
interface AssetEntry {
name: string;
path: string;
contentType: string;
}
async function main (): Promise<void> {
console.log('📦 PR Release Publisher\n');
const token = getEnv('RELEASE_PAT', true);
const prNumber = getEnv('PR_NUMBER', true);
const prSha = getEnv('PR_SHA', true);
const version = getEnv('NAPCAT_VERSION') || 'unknown';
const artifactsDir = getEnv('ARTIFACTS_DIR') || './artifacts';
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
const installerRepo = getEnv('INSTALLER_REPO') || 'NapNeko/NapCat-Installer';
const installerBranch = getEnv('INSTALLER_BRANCH') || 'main';
const [releaseOwner, releaseRepoName] = releaseRepo.split('/');
const shortSha = prSha.substring(0, 7);
const tag = `pr-${prNumber}-${shortSha}`;
const releaseName = `PR #${prNumber} (${shortSha})`;
const downloadBase = `https://github.com/${releaseRepo}/releases/download/${tag}`;
console.log(` Tag: ${tag}`);
console.log(` Repo: ${releaseRepo}`);
console.log(` Version: ${version}`);
console.log(` SHA: ${shortSha}\n`);
const github = new GitHubAPI(token);
const releaseDir = resolve('./release-assets'); // 使用绝对路径,避免 zip cwd 切换后相对路径解析错误
mkdirSync(releaseDir, { recursive: true });
// ---- 打包构建产物 ----
const artifacts = ['NapCat.Framework', 'NapCat.Shell'];
for (const name of artifacts) {
const dir = join(artifactsDir, name);
if (existsSync(dir)) {
const zipPath = join(releaseDir, `${name}.zip`);
console.log(`📦 Packing ${name}...`);
execSync(`zip -qr "${zipPath}" .`, { cwd: dir, stdio: 'inherit' });
console.log(` ✓ ${name}.zip\n`);
} else {
console.log(` ⚠ ${name} 目录不存在,跳过\n`);
}
}
// ---- 拉取并修改安装脚本 ----
console.log('📜 Fetching install.sh...');
const scriptUrl = `https://raw.githubusercontent.com/${installerRepo}/${installerBranch}/script/install.sh`;
try {
const response = await fetch(scriptUrl);
if (response.ok) {
let script = await response.text();
// 替换下载链接(保留代理前缀 ${target_proxy:+${target_proxy}/})
const shellUrl = `${downloadBase}/NapCat.Shell.zip`;
const originalScript = script;
script = script.replace(
/napcat_download_url="\$\{target_proxy:\+\$\{target_proxy\}\/\}https:\/\/github\.com\/NapNeko\/NapCatQQ\/releases\/latest\/download\/NapCat\.Shell\.zip"/g,
`napcat_download_url="\${target_proxy:+\${target_proxy}/}${shellUrl}"`
);
if (script === originalScript) {
console.log(' ⚠ Warning: URL replacement did not match - install.sh format may have changed');
}
const scriptPath = join(releaseDir, 'install.sh');
writeFileSync(scriptPath, script, { mode: 0o755 });
console.log(` ✓ Patched download URL -> ${shellUrl}\n`);
} else {
console.log(` ⚠ Failed to fetch install.sh: ${response.status}\n`);
}
} catch (e) {
console.log(` ⚠ Failed to fetch install.sh: ${(e as Error).message}\n`);
}
// ---- 收集所有要上传的文件 ----
const assets: AssetEntry[] = [];
for (const file of readdirSync(releaseDir)) {
const ext = file.split('.').pop()?.toLowerCase();
const contentType = ext === 'zip' ? 'application/zip' : ext === 'sh' ? 'application/x-sh' : 'application/octet-stream';
assets.push({ name: file, path: join(releaseDir, file), contentType });
}
console.log(`📋 Assets to upload: ${assets.map(a => a.name).join(', ')}\n`);
// ---- 删除旧 release ----
console.log('🗑️ Checking for existing release...');
const existing = await github.getReleaseByTag(releaseOwner, releaseRepoName, tag);
if (existing) {
console.log(` Deleting existing release (id=${existing.id})...`);
await github.deleteRelease(releaseOwner, releaseRepoName, existing.id);
await github.deleteRef(releaseOwner, releaseRepoName, `tags/${tag}`);
console.log(' ✓ Deleted\n');
} else {
console.log(' No existing release\n');
}
// ---- 创建 Release ----
const directInstallUrl = `${downloadBase}/install.sh`;
const proxyInstallUrl = toProxyUrl(directInstallUrl);
const releaseBody = [
`## NapCat PR #${prNumber} 测试版本`,
'',
`- **版本**: \`${version}\``,
`- **提交**: \`${prSha}\``,
`- **来源**: [NapCatQQ PR #${prNumber}](https://github.com/NapNeko/NapCatQQ/pull/${prNumber})`,
'',
'### 快速安装 (Linux)',
'',
'**直连(需要能访问 GitHub)**',
'```bash',
`curl -sSL ${directInstallUrl} | bash`,
'```',
'',
'**加速(国内推荐,ghfast.top)**',
'```bash',
`curl -sSL ${proxyInstallUrl} | bash`,
'```',
'',
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。',
].join('\n');
console.log('🚀 Creating release...');
const release = await github.createRelease(
releaseOwner, releaseRepoName, tag, releaseName, releaseBody, true
);
console.log(` ✓ Release created: ${release.html_url}\n`);
// ---- 上传资产 ----
console.log('📤 Uploading assets...');
for (const asset of assets) {
const data = readFileSync(asset.path);
const uploaded = await github.uploadReleaseAsset(
release.upload_url, asset.name, data, asset.contentType
);
console.log(` ✓ ${asset.name} -> ${uploaded.browser_download_url}`);
}
console.log(`\n✅ Release published: ${release.html_url}`);
// 输出供后续 job 使用
setOutput('release_url', release.html_url);
setOutput('release_tag', tag);
setOutput('install_url', `${downloadBase}/install.sh`);
}
main().catch((error) => {
console.error('❌ Error:', error);
process.exit(1);
});
+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}`);
-153
View File
@@ -1,153 +0,0 @@
name: Auto Release Docker
on:
release:
types: [published]
jobs:
publish-schema:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Get Version
id: get_version
run: |
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
version=${latest_tag#v}
echo "version=${version}" >> $GITHUB_ENV
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
echo "Debug: Version is ${version}"
- name: Install Dependencies
run: pnpm install --frozen-lockfile
- name: Build napcat-schema
run: |
cd packages/napcat-schema
pnpm run build:openapi
- name: Checkout NapCatDocs
uses: actions/checkout@v4
with:
repository: NapNeko/NapCatDocs
token: ${{ secrets.NAPCAT_BUILD }}
path: napcat-docs
- name: Copy OpenAPI Schema
run: |
mkdir -p napcat-docs/src/api/${{ env.version }}
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
- name: Commit and Push
run: |
cd napcat-docs
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add src/api/${{ env.version }}/openapi.json
git commit -m "chore: update OpenAPI schema for version ${{ env.version }}" || echo "No changes to commit"
git push
shell-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
framework-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Framework-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
-d '{"ref":"main"}'
appimage-shell-docker:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Get Latest NapCat Version
id: get_version
run: |
# 获取当前仓库的最新 tag
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
# 输出调试信息
echo "Debug: Latest NapCat Version is ${latest_tag}"
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_version_x86_64=${QQ_VERSION_X86_64}, qq_version_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${QQ_VERSION_X86_64}\",\"qq_version_arm64\":\"${QQ_VERSION_ARM64}\"}}"
node-shell-docker:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Get Latest NapCat Version
id: get_version
run: |
# 获取当前仓库的最新 tag
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
# 输出调试信息
echo "Debug: Latest NapCat Version is ${latest_tag}"
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
- name: Trigger Release NapCat AppImage Workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ env.latest_tag }}
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
run: |
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
+84
View File
@@ -0,0 +1,84 @@
name: Build NapCat Artifacts
on:
workflow_dispatch:
push:
branches:
- main
permissions: write-all
jobs:
typecheck-and-test:
name: Type Check & Test
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Install Dependencies
run: |
npm i -g pnpm
pnpm i
- name: Type Check
run: pnpm run typecheck
- name: Run Tests
run: pnpm test
build:
name: Build NapCat.${{ matrix.target.name }}
needs: typecheck-and-test
runs-on: ubuntu-latest
strategy:
matrix:
target:
- name: Framework
build_cmd: build:framework
src_dir: packages/napcat-framework/dist
dist_dir: framework-dist
- name: Shell
build_cmd: build:shell
src_dir: packages/napcat-shell/dist
dist_dir: shell-dist
steps:
- name: Clone Main Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Generate Version
run: |
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run ${{ matrix.target.build_cmd }}
pnpm --filter napcat-plugin-builtin run build || exit 1
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v6
with:
name: NapCat.${{ matrix.target.name }}
path: ${{ matrix.target.dist_dir }}
@@ -13,7 +13,7 @@
# - PR 代码单独 checkout 到 workspace 目录
# =============================================================================
name: PR Build
name: Build PR
# =============================================================================
# 触发条件
@@ -73,14 +73,14 @@ jobs:
steps:
# 仅 checkout 脚本目录,加快速度
- name: Checkout scripts
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
# 使用 Node.js 24 以支持原生 TypeScript 执行
- name: Setup Node.js 24
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 24
@@ -102,13 +102,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 24
@@ -137,7 +137,7 @@ jobs:
# 【安全】先从 base 分支 checkout 构建脚本
# 这样即使 PR 中修改了脚本,也不会被执行
- name: Checkout scripts from base
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
@@ -145,15 +145,15 @@ jobs:
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 24
@@ -170,6 +170,7 @@ jobs:
SHORT_SHA="${SHORT_SHA::7}"
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
@@ -186,11 +187,11 @@ jobs:
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: workspace/framework-dist
retention-days: 7 # 保留 7 天
retention-days: 5 # 保留 5 天(仓库上限)
# ---------------------------------------------------------------------------
# Job 4: 构建 Shell 包
@@ -208,7 +209,7 @@ jobs:
steps:
# 【安全】先从 base 分支 checkout 构建脚本
- name: Checkout scripts from base
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
@@ -216,15 +217,15 @@ jobs:
# 将 PR 代码 checkout 到单独的 workspace 目录
- name: Checkout PR code
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
repository: ${{ needs.check-build.outputs.pr_head_repo }}
ref: ${{ needs.check-build.outputs.pr_sha }}
path: workspace
fetch-depth: 0 # 需要完整历史来获取 tags
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Setup Node.js 24
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 24
@@ -258,11 +259,11 @@ jobs:
# 构建成功时上传产物
- name: Upload Artifact
if: steps.build.outcome == 'success'
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell
path: workspace/shell-dist
retention-days: 7 # 保留 7 天
retention-days: 5 # 保留 5 天(仓库上限)
# ---------------------------------------------------------------------------
# Job 5: 更新评论为构建结果
@@ -271,18 +272,18 @@ jobs:
# 使用 always() 确保即使构建失败/取消也会执行
# ---------------------------------------------------------------------------
update-comment-result:
needs: [check-build, update-comment-building, build-framework, build-shell]
needs: [check-build, update-comment-building, build-framework, build-shell, publish-pr-release]
if: always() && needs.check-build.outputs.should_build == 'true'
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v4
uses: actions/setup-node@v6
with:
node-version: 24
@@ -300,4 +301,115 @@ jobs:
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
# PR Release 信息(用于在评论中显示安装命令)
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
# ---------------------------------------------------------------------------
# Job 6: 发布 PR 构建产物到 napcat-pr-release 仓库
# ---------------------------------------------------------------------------
# 将所有构建产物打包 + 从 NapCat-Installer 拉取并修改安装脚本,
# 一起发布为 GitHub Release(公开可下载,无需登录)。
# Release 会由 napcat-pr-release 仓库的定时任务在 24h 后自动清理。
# ---------------------------------------------------------------------------
publish-pr-release:
needs: [check-build, build-framework, build-shell]
if: always() && needs.check-build.outputs.should_build == 'true' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
runs-on: ubuntu-latest
outputs:
release_url: ${{ steps.publish.outputs.release_url }}
release_tag: ${{ steps.publish.outputs.release_tag }}
install_url: ${{ steps.publish.outputs.install_url }}
publish_status: ${{ steps.publish.outcome }} # 'success' | 'failure' | 'skipped'
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Download Framework artifact
if: needs.build-framework.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Framework
path: ./artifacts/NapCat.Framework
- name: Download Shell artifact
if: needs.build-shell.outputs.status == 'success'
uses: actions/download-artifact@v6
with:
name: NapCat.Shell
path: ./artifacts/NapCat.Shell
- name: Publish release
id: publish
continue-on-error: true
env:
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
ARTIFACTS_DIR: ./artifacts
run: |
if [ -z "${RELEASE_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 PR Release 发布"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-publish-release.ts
# 将修改后的安装脚本也上传为 CI artifact(自动过期)
- name: Upload install script as artifact
if: steps.publish.outcome == 'success'
uses: actions/upload-artifact@v6
with:
name: install-script
path: ./release-assets/install.sh
retention-days: 5
if-no-files-found: ignore
# ---------------------------------------------------------------------------
# Job 7: 触发 NapCat-Docker 仓库的 PR 测试镜像构建
# ---------------------------------------------------------------------------
# 仅当 Shell 构建成功、且 Release 已发布时触发。
# Docker 构建从公开 Release 下载产物,无需跨仓 artifact PAT。
# ---------------------------------------------------------------------------
trigger-docker:
needs: [check-build, build-shell, publish-pr-release]
if: needs.check-build.outputs.should_build == 'true' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
runs-on: ubuntu-latest
steps:
- name: Checkout scripts
uses: actions/checkout@v5
with:
sparse-checkout: .github/scripts
sparse-checkout-cone-mode: false
- name: Setup Node.js 24
uses: actions/setup-node@v6
with:
node-version: 24
- name: Dispatch docker build
continue-on-error: true
env:
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
SOURCE_REPO: ${{ github.repository }}
RELEASE_REPO: NapNeko/napcat-pr-release
run: |
if [ -z "${DISPATCH_PAT}" ]; then
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 Docker 测试镜像构建"
exit 0
fi
node --experimental-strip-types .github/scripts/pr-docker-dispatch.ts
-96
View File
@@ -1,96 +0,0 @@
name: Build NapCat Artifacts
on:
workflow_dispatch:
push:
branches:
- main
permissions: write-all
jobs:
Build-Framework:
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Use Node.js 20.X
uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Generate Version
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.Framework
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm run typecheck || exit 1
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Framework
path: framework-dist
Build-Shell:
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # 需要完整历史来获取 tags
- name: Use Node.js 20.X
uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Generate Version
run: |
# 获取最近的 release tag (格式: vX.X.X)
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
# 去掉 v 前缀
BASE_VERSION="${LATEST_TAG#v}"
SHORT_SHA="${GITHUB_SHA::7}"
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
echo "Latest tag: ${LATEST_TAG}"
echo "Build version: ${VERSION}"
- name: Build NapCat.Shell
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
run: |
npm i -g pnpm
pnpm i
pnpm run typecheck || exit 1
pnpm test || exit 1
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Shell
path: shell-dist
+153
View File
@@ -0,0 +1,153 @@
name: Release Downstream
on:
workflow_dispatch:
inputs:
tag_name:
description: 'Release tag name (e.g., v4.10.7)'
required: true
type: string
env:
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
jobs:
get-version:
runs-on: ubuntu-latest
outputs:
latest_tag: ${{ steps.get_version.outputs.latest_tag }}
version: ${{ steps.get_version.outputs.version }}
steps:
- name: Checkout Repository
uses: actions/checkout@v5
- name: Get Latest NapCat Version
id: get_version
run: |
if [ -n "${{ inputs.tag_name }}" ]; then
latest_tag="${{ inputs.tag_name }}"
else
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
fi
version=${latest_tag#v}
echo "Debug: Latest NapCat Version is ${latest_tag}, version is ${version}"
echo "latest_tag=${latest_tag}" >> $GITHUB_OUTPUT
echo "version=${version}" >> $GITHUB_OUTPUT
publish-schema:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: '20'
- name: Setup pnpm
uses: pnpm/action-setup@v4
with:
version: 9
- name: Install Dependencies
run: pnpm install --frozen-lockfile
- name: Build napcat-schema
run: |
cd packages/napcat-schema
pnpm run build:openapi
- name: Checkout NapCatDocs
uses: actions/checkout@v5
with:
repository: NapNeko/NapCatDocs
token: ${{ secrets.NAPCAT_BUILD }}
path: napcat-docs
- name: Copy OpenAPI Schema
run: |
VERSION="${{ needs.get-version.outputs.version }}"
mkdir -p napcat-docs/src/api/${VERSION}
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${VERSION}/openapi.json
echo "OpenAPI schema copied to napcat-docs/src/api/${VERSION}/openapi.json"
- name: Commit and Push
run: |
VERSION="${{ needs.get-version.outputs.version }}"
cd napcat-docs
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add src/api/${VERSION}/openapi.json
git commit -m "chore: update OpenAPI schema for version ${VERSION}" || echo "No changes to commit"
git push
shell-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
-d '{"ref":"main"}'
framework-docker:
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat-Framework-Docker docker-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
run: |
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
-d '{"ref":"main"}'
appimage:
needs: get-version
runs-on: ubuntu-latest
steps:
- name: Trigger NapCat AppImage build workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
run: |
echo "Debug: Triggering NapCat AppImage with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_version_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
node-shell:
needs: get-version
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
steps:
- name: Trigger NapCat NodeLoader release workflow
run: |
echo "Debug: Triggering NapCat NodeLoader release with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
- name: Trigger NapCat NodeLoader docker workflow
run: |
echo "Debug: Triggering NapCat NodeLoader docker with napcat_version=${NAPCAT_VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
@@ -1,115 +1,73 @@
name: Release NapCat
name: Release Publish
on:
workflow_dispatch:
push:
tags:
- 'v*'
inputs:
version:
description: 'Release version tag (e.g., v4.10.7)'
required: true
type: string
permissions: write-all
env:
OPENROUTER_API_URL: https://91vip.futureppo.top/v1/chat/completions
OPENROUTER_MODEL: "deepseek-v3.2-chat"
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
RELEASE_NAME: "NapCat"
jobs:
# 验证版本号格式
validate-version:
runs-on: ubuntu-latest
outputs:
valid: ${{ steps.check.outputs.valid }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Validate semantic version
id: check
run: |
TAG="${GITHUB_REF#refs/tags/}"
echo "Checking tag: $TAG"
# 语义化版本正则表达式
# 支持: v1.0.0, v1.0.0-beta, v1.0.0-rc.1, v1.0.0-alpha.1+build.123
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
echo "✅ Valid semantic version: $TAG"
echo "valid=true" >> $GITHUB_OUTPUT
echo "version=$TAG" >> $GITHUB_OUTPUT
else
echo "❌ Invalid version format: $TAG"
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
echo "valid=false" >> $GITHUB_OUTPUT
exit 1
fi
Build-Framework:
needs: validate-version
if: needs.validate-version.outputs.valid == 'true'
build:
name: Build NapCat.${{ matrix.target.name }}
runs-on: ubuntu-latest
strategy:
matrix:
target:
- name: Framework
build_cmd: build:framework
src_dir: packages/napcat-framework/dist
dist_dir: framework-dist
- name: Shell
build_cmd: build:shell
src_dir: packages/napcat-shell/dist
dist_dir: shell-dist
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
- name: Use Node.js 20.X
uses: actions/setup-node@v4
uses: actions/checkout@v5
with:
ref: ${{ inputs.version }}
- name: Use Node.js 20.x
uses: actions/setup-node@v6
with:
node-version: 20.x
- name: Build NapCat.Framework
- name: Build NapCat.${{ matrix.target.name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:framework
pnpm run ${{ matrix.target.build_cmd }}
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-framework/dist framework-dist
cd framework-dist
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
cd ${{ matrix.target.dist_dir }}
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Framework
path: framework-dist
name: NapCat.${{ matrix.target.name }}
path: ${{ matrix.target.dist_dir }}
Build-Shell:
needs: validate-version
if: needs.validate-version.outputs.valid == 'true'
assemble-windows-node:
needs: build
runs-on: ubuntu-latest
steps:
- name: Clone Main Repository
uses: actions/checkout@v4
- name: Use Node.js 20.X
uses: actions/setup-node@v4
- uses: actions/checkout@v5
with:
node-version: 20.x
- name: Build NapCat.Shell
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
npm i -g pnpm
pnpm i
pnpm --filter napcat-webui-frontend run build || exit 1
pnpm run build:shell
pnpm --filter napcat-plugin-builtin run build || exit 1
mv packages/napcat-shell/dist shell-dist
cd shell-dist
npm install --omit=dev
rm ./package-lock.json || exit 0
- name: Upload Artifact
uses: actions/upload-artifact@v4
with:
name: NapCat.Shell
path: shell-dist
Download-QNX64:
needs: Build-Shell
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
ref: ${{ inputs.version }}
- name: Download Artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v7
with:
path: ./artifacts
@@ -118,35 +76,48 @@ jobs:
sudo apt update
sudo apt install -y aria2 unzip zip p7zip-full curl jq
- name: Download and Assemble NapCat.Shell.Windows.Node.zip
- name: Cache QQ and Node.js downloads
id: cache-downloads
uses: actions/cache@v4
with:
path: /tmp/napcat-downloads
key: napcat-downloads-qq9.9.27.45627-node22.11.0
- name: Download QQ and Node.js
if: steps.cache-downloads.outputs.cache-hit != 'true'
run: |
set -euo pipefail
mkdir -p /tmp/napcat-downloads
cd /tmp/napcat-downloads
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
echo "Downloading QQ installer..."
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
echo "Downloading Node.js $NODE_VER..."
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
- name: Assemble NapCat.Shell.Windows.Node.zip
run: |
set -euo pipefail
TMPDIR=$(mktemp -d)
cd "$TMPDIR"
CACHE_DIR="/tmp/napcat-downloads"
# -----------------------------
# 1) 下载 QQ x64
# 1) 解压 QQ x64
# -----------------------------
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
QQ_ZIP="$(basename "$NT_URL")"
echo "Downloading QQ installer: $QQ_ZIP"
aria2c -x16 -s16 -k1M -o "$QQ_ZIP" "$NT_URL"
QQ_EXTRACT="$TMPDIR/qq_extracted"
mkdir -p "$QQ_EXTRACT"
7z x -y -o"$QQ_EXTRACT" "$QQ_ZIP" >/dev/null
7z x -y -o"$QQ_EXTRACT" "$CACHE_DIR/QQ_x64.exe" >/dev/null
# -----------------------------
# 2) 下载 Node.js Windows x64 zip 22.11.0
# 2) 解压 Node.js Windows x64
# -----------------------------
NODE_VER="22.11.0"
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
NODE_ZIP="node-v$NODE_VER-win-x64.zip"
aria2c -x1 -s1 -k1M -o "$NODE_ZIP" "$NODE_URL"
NODE_EXTRACT="$TMPDIR/node_extracted"
mkdir -p "$NODE_EXTRACT"
unzip -q "$NODE_ZIP" -d "$NODE_EXTRACT"
unzip -q "$CACHE_DIR/node-win-x64.zip" -d "$NODE_EXTRACT"
# -----------------------------
# 3) 创建输出目录
@@ -180,6 +151,7 @@ jobs:
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/napcat.bat" "$OUT_DIR/" || true
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/index.js" "$OUT_DIR/" || true
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/QQNT.dll" "$OUT_DIR/" || true
# -----------------------------
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
# -----------------------------
@@ -187,22 +159,22 @@ jobs:
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
- name: Upload Artifact
uses: actions/upload-artifact@v4
uses: actions/upload-artifact@v6
with:
name: NapCat.Shell.Windows.Node
path: NapCat.Shell.Windows.Node
release-napcat:
needs: [Build-Framework, Build-Shell, Download-QNX64]
needs: [build, assemble-windows-node]
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
uses: actions/checkout@v5
with:
fetch-depth: 0
fetch-depth: 0
- name: Download Artifacts
uses: actions/download-artifact@v4
uses: actions/download-artifact@v7
with:
path: ./artifacts
@@ -218,18 +190,18 @@ jobs:
[ -d NapCat.Shell.Windows.Node ] && (cd NapCat.Shell.Windows.Node && zip -qr ../../NapCat.Shell.Windows.Node.zip .)
cd ..
- name: Generate release note via OpenRouter
- name: Generate release note
env:
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
OPENROUTER_API_URL: ${{ env.OPENROUTER_API_URL }}
OPENROUTER_MODEL: ${{ env.OPENROUTER_MODEL }}
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
GITHUB_OWNER: "NapNeko"
GITHUB_REPO: "NapCatQQ"
run: |
set -euo pipefail
# 当前 tag
CURRENT_TAG="${GITHUB_REF#refs/tags/}"
CURRENT_TAG="${{ inputs.version }}"
echo "Current tag: $CURRENT_TAG"
# 从 GitHub API 获取 tag 列表
@@ -248,7 +220,7 @@ jobs:
done
if [ -z "$PREV_TAG" ]; then
echo "⚠️ Could not find previous tag for $CURRENT_TAG, using first commit"
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
fi
@@ -259,7 +231,6 @@ jobs:
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
# 获取 commit,使用更清晰的格式
# 格式: <type>: <subject> (<hash>)
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
@@ -268,15 +239,15 @@ jobs:
# 获取文件变化统计
echo "Getting file change statistics..."
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
# 获取总体统计(最后一行)
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
echo "Summary: $SUMMARY_LINE"
# 获取每个文件的变化(去掉最后一行汇总)
# 截断过长的输出(最多50个文件,每行最多80字符)
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
# 如果文件变化太多,进一步精简:只保留主要目录的变化
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
if [ "$FILE_COUNT" -gt 50 ]; then
@@ -289,28 +260,27 @@ jobs:
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
$DIR_STATS"
fi
echo "File changes:"
echo "$FILE_CHANGES"
# 获取具体代码变化(关键文件的diff)
echo "Getting code diff for key files..."
# 定义关键目录(优先展示这些目录的变化)
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
# 获取变更的关键文件列表(排除测试、配置等)
# 使用 || true 防止 grep 无匹配时返回非零退出码
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
grep -E "\.(ts|js)$" || true | \
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
head -15) || true
CODE_DIFF=""
DIFF_CHAR_LIMIT=6000 # 总diff字符限制
DIFF_CHAR_LIMIT=6000
CURRENT_CHARS=0
if [ -n "$KEY_FILES" ]; then
for file in $KEY_FILES; do
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
@@ -318,21 +288,19 @@ jobs:
[... 更多文件变化已截断 ...]"
break
fi
# 获取单个文件的diff,限制每个文件最多50行
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
FILE_DIFF_LEN=${#FILE_DIFF}
# 如果单个文件diff超过1500字符,截断
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
FILE_DIFF="$FILE_DIFF
[... 文件 $file 变化已截断 ...]"
fi
if [ -n "$FILE_DIFF" ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
@@ -341,19 +309,19 @@ jobs:
fi
done
fi
# 如果没有关键文件变化,获取前5个变更文件的diff
if [ -z "$CODE_DIFF" ]; then
echo "No key files changed, getting top changed files..."
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
grep -E "\.(ts|js|yml|md)$" | head -5) || true
if [ -n "$TOP_FILES" ]; then
for file in $TOP_FILES; do
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
CODE_DIFF="$CODE_DIFF
### $file
\`\`\`diff
$FILE_DIFF
@@ -362,12 +330,12 @@ jobs:
done
fi
fi
# 如果仍然没有代码变化,添加说明
if [ -z "$CODE_DIFF" ]; then
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
fi
echo "Code diff preview:"
echo "$CODE_DIFF" | head -50
@@ -378,16 +346,16 @@ jobs:
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
USER_CONTENT="当前版本: $CURRENT_TAG
上一版本: $PREV_TAG
## 提交列表
$COMMITS
## 文件变化统计
$SUMMARY_LINE
## 变更文件列表
$FILE_CHANGES
## 关键代码变化
$CODE_DIFF"
@@ -395,20 +363,19 @@ jobs:
BODY=$(jq -n \
--arg system "$SYSTEM_PROMPT" \
--arg user "$USER_CONTENT" \
--arg model "$OPENROUTER_MODEL" \
--arg model "$OPENAI_MODEL" \
'{model: $model, messages:[{role:"system", content:$system},{role:"user", content:$user}], temperature:0.2, max_tokens:5000}')
echo "=== OpenRouter request body ==="
echo "=== request body ==="
echo "$BODY" | jq .
# 调用 OpenRouter
if RESPONSE=$(curl -s -X POST "$OPENROUTER_API_URL" \
if RESPONSE=$(curl -s -X POST "$OPENAI_API_URL" \
-H "Authorization: Bearer $OPENAI_KEY" \
-H "Content-Type: application/json" \
-d "$BODY"); then
echo "=== raw response ==="
echo "$RESPONSE"
echo "=== OpenRouter raw response ==="
echo "$RESPONSE"
echo "=== parsed response ==="
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
echo "$RESPONSE" | jq .
else
@@ -419,38 +386,34 @@ jobs:
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
if [ -z "$RELEASE_BODY" ]; then
echo "❌ OpenRouter failed to generate release note, using default.md"
# 替换默认模板中的版本占位符
echo "LLM failed to generate release note, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
else
# 后处理:确保版本号正确,并添加比较链接
echo -e "$RELEASE_BODY" > CHANGELOG.md
# 替换可能的占位符
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
fi
else
echo "❌ Curl failed, using default.md"
echo "Curl failed, using default.md"
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
fi
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 }}
tag_name: ${{ inputs.version }}
name: NapCat ${{ inputs.version }}
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
env:
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
@@ -459,7 +422,6 @@ jobs:
pnpm i
pnpm run build:openapi
# 使用 jq 安全地构建大型 JSON 数据并保存到文件
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
'{
input: $input,
@@ -472,10 +434,48 @@ jobs:
}
}' > apifox_payload.json
# 通过文件形式发送数据,避免命令行长度限制
curl --location -g --request POST 'https://api.apifox.com/v1/projects/5348325/import-openapi?locale=zh-CN' \
--header 'X-Apifox-Api-Version: 2024-03-28' \
--header "Authorization: Bearer $APIFOX_TOKEN" \
--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="${{ inputs.version }}"
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
- name: Trigger downstream release workflows
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
VERSION: ${{ inputs.version }}
run: |
echo "Triggering release-downstream workflow with tag_name=${VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-downstream.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"tag_name\":\"${VERSION}\"}}"
+53
View File
@@ -0,0 +1,53 @@
name: Release Tag
on:
workflow_dispatch:
push:
tags:
- 'v*'
permissions: write-all
jobs:
validate-version:
runs-on: ubuntu-latest
outputs:
valid: ${{ steps.check.outputs.valid }}
version: ${{ steps.check.outputs.version }}
steps:
- name: Validate semantic version
id: check
run: |
TAG="${GITHUB_REF#refs/tags/}"
echo "Checking tag: $TAG"
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
echo "Valid semantic version: $TAG"
echo "valid=true" >> $GITHUB_OUTPUT
echo "version=$TAG" >> $GITHUB_OUTPUT
else
echo "Invalid version format: $TAG"
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
echo "valid=false" >> $GITHUB_OUTPUT
exit 1
fi
trigger-release:
needs: [validate-version]
if: needs.validate-version.outputs.valid == 'true'
runs-on: ubuntu-latest
steps:
- name: Trigger release-publish workflow
env:
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
VERSION: ${{ needs.validate-version.outputs.version }}
run: |
echo "Triggering release-publish workflow with version=${VERSION}"
curl -X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_TOKEN" \
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-publish.yml/dispatches \
-d "{\"ref\":\"main\",\"inputs\":{\"version\":\"${VERSION}\"}}"
+1 -1
View File
@@ -6,7 +6,7 @@
"vite.config.ts": "vite*.ts",
"README.md": "CODE_OF_CONDUCT.md, RELEASES.md, CONTRIBUTING.md, CHANGELOG.md, SECURITY.md",
"tsconfig.json": "tsconfig.*.json, env.d.ts",
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, logo.png, .gitignore, LICENSE"
},
"css.customData": [
".vscode/tailwindcss.json"
+41 -25
View File
@@ -5,41 +5,47 @@
_Modern protocol-side framework implemented based on NTQQ._
> Where clouds rise and winds are born, the heart yearns for distant lands yet untraveled.
English | [简体中文](./docs/README_zh-CN.md) | [繁體中文](./docs/README_zh-TW.md) | [日本語](./docs/README_ja.md) | [한국어](./docs/README_ko.md) | [Русский](./docs/README_ru.md) | [العربية](./docs/README_ar.md)
> 云起兮风生,心向远方兮路未曾至.
</div>
---
## 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.
## New Feature
在 v4.8.115+ 版本开始
1. NapCatQQ 支持 [Stream Api](https://napneko.github.io/develop/file)
2. NapCatQQ 推荐 message_id/user_id/group_id 均使用字符串类型
- [1] 解决 Docker/跨设备/大文件 的多媒体上下传问题
- [2] 采用字符串可以解决扩展到int64的问题,同时也可以解决部分语言(如JavaScript)对大整数支持不佳的问题,增加极少成本。
## Welcome
- NapCatQQ is a modern implementation of the Bot protocol based on NTQQ.
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
## Features
## Feature
- **Easy to Use**
- Beginners can get started effortlessly.
- 作为初学者能够轻松使用.
- **Quick and Efficient**
- Runs for extended periods on low-memory systems.
- 在低内存操作系统长时运行.
- **Rich API Interface**
- Fully implements most standard interfaces.
- 完整实现了大部分标准接口.
- **Stable and Reliable**
- Continuous and stable development and maintenance.
- 持续稳定的开发与维护.
## Quick Start
Download the latest version from the [Release](https://github.com/NapNeko/NapCatQQ/releases/) page.
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
**First-time users** should make sure to read the documentation below for a usage guide.
**首次使用**请务必查看如下文档看使用教程
> This is a non-profit project. For integration issues, basic questions, or underlying framework issues, please search for solutions on your own — this project's community does not provide such support.
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
## Links
## Link
| Docs | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
@@ -47,31 +53,41 @@ Download the latest version from the [Release](https://github.com/NapNeko/NapCat
| Docs | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| QQ Group | [![NapCat Family Group 4](https://img.shields.io/badge/NapCat%20Family%20Group%204-Join-blue)](https://qm.qq.com/q/E4nfkGD6oK) | [![NapCat Family Group 3](https://img.shields.io/badge/NapCat%20Family%20Group%203-Join-blue)](https://qm.qq.com/q/XyiyGPqa42) | [![NapCat Family Group 2](https://img.shields.io/badge/NapCat%20Family%20Group%202-Join-blue)](https://qm.qq.com/q/gq18RH7o7S) | [![NapCat Family Group 1](https://img.shields.io/badge/NapCat%20Family%20Group%201-Join-blue)](https://qm.qq.com/q/VwpnklcXqo) |
|:-:|:-:|:-:|:-:|:-:|
| Telegram | [![Telegram](https://img.shields.io/badge/Telegram-napcatqq-blue)](https://t.me/napcatqq) |
|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 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.
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
下面的QQ Group 无需密钥,随时清理不活跃人员和Bot,仅500人容量。
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
## Thanks
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — Great support for this project; some code was referenced (with permission)
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — An LLM Bot framework that perfectly integrates with this project
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — A cyber companion Bot framework
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — A message export tool based on NapCat
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
- And most importantly, thank you — the person reading this right now~
- 不过最最重要的 还是需要感谢屏幕前的你哦~
---
## License
This project is open-sourced under a hybrid license. When using this project, please note the following:
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
1. Third-party library code or modified portions follow their original open-source licenses.
2. This project has obtained authorization from certain projects and is not subject to some restrictions.
3. The remaining logic code of the project is governed by the [repository license](./LICENSE).
1. 第三方库代码或修改部分遵循其原始开源许可.
2. 本项目获取部分项目授权而不受部分约束
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
**This repository is solely intended to improve usability and implement message push features. Furthermore, developing any project based on NapCat code without prior authorization from the repository's main author is prohibited. Please comply with local laws and regulations when using this project. Any issues arising from misuse are the responsibility of the user and anyone providing tutorials for unauthorized use.**
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
-81
View File
@@ -1,81 +0,0 @@
<div dir="rtl">
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=left />
<div align="center">
# NapCat
_إطار عمل حديث على جانب البروتوكول مبني على NTQQ._
> حيث تنهض السحب وتولد الرياح، يتوق القلب إلى أراضٍ بعيدة لم تُسلك بعد.
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | العربية
</div>
---
## إعلان
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com. لن يتم إنشاء مجموعات مجتمع عامة خلال هذه الفترة، لكن NapCat يضمن استمرار التحديثات المنتظمة.
## مرحباً
- NapCatQQ هو تطبيق حديث لبروتوكول Bot مبني على NTQQ
## المميزات
- **سهل الاستخدام**
- يمكن للمبتدئين البدء بسهولة.
- **سريع وفعال**
- يعمل لفترات طويلة على أنظمة ذات ذاكرة منخفضة.
- **واجهة API غنية**
- تنفيذ كامل لمعظم الواجهات القياسية.
- **مستقر وموثوق**
- تطوير وصيانة مستمرة ومستقرة.
## البداية السريعة
قم بتنزيل أحدث إصدار من صفحة [Release](https://github.com/NapNeko/NapCatQQ/releases/)
**للمستخدمين لأول مرة** تأكد من قراءة الوثائق أدناه للحصول على دليل الاستخدام
> هذا مشروع غير ربحي. للمشاكل المتعلقة بالتكامل والأسئلة الأساسية ومشاكل إطار العمل الأساسي، يرجى البحث عن الحلول بنفسك — مجتمع هذا المشروع لا يقدم مثل هذا الدعم.
## الروابط
| الوثائق | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| الوثائق | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> يرجى عدم ذكر هذا المشروع في مجتمعات أخرى (بما في ذلك مشاريع البروتوكول الأخرى / مشاريع التطبيقات ذات الصلة) لتجنب الخلافات. إذا كانت لديك اقتراحات، يرجى مناقشتها في المجموعة الرسمية أو تقديم PR.
## شكر وتقدير
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — دعم كبير لهذا المشروع؛ تمت الإشارة إلى بعض الأكواد (بإذن)
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — إطار عمل LLM Bot متوافق تماماً مع هذا المشروع
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — إطار عمل Bot رفيق سيبراني
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — أداة تصدير الرسائل مبنية على NapCat
- والأهم من ذلك كله، شكراً لك — أنت الذي تقرأ هذا الآن~
---
## الرخصة
هذا المشروع مفتوح المصدر بموجب رخصة هجينة. عند استخدام هذا المشروع، يرجى ملاحظة ما يلي:
1. كود المكتبات الخارجية أو الأجزاء المعدلة تخضع لرخصها مفتوحة المصدر الأصلية.
2. حصل هذا المشروع على إذن من بعض المشاريع ولا يخضع لبعض القيود.
3. باقي الكود المنطقي للمشروع يخضع [لرخصة هذا المستودع](../LICENSE).
**هذا المستودع مخصص فقط لتحسين سهولة الاستخدام وتنفيذ ميزات دفع الرسائل. علاوة على ذلك، يُحظر تطوير أي مشروع بناءً على كود NapCat دون إذن مسبق من المؤلف الرئيسي للمستودع. يرجى الامتثال للقوانين واللوائح المحلية عند الاستخدام. أي مشاكل ناتجة عن سوء الاستخدام تقع على عاتق المستخدم ومن يقدم تعليمات الاستخدام غير المصرح به.**
</div>
-77
View File
@@ -1,77 +0,0 @@
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
<div align="center">
# NapCat
_NTQQをベースにした最新のプロトコル側フレームワーク._
> 雲起きて風生じ、心は遠方を向けど路は未だ至らず.
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | 日本語 | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
</div>
---
## お知らせ
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。この期間中、公開コミュニティグループは設立しませんが、NapCat は通常通りの更新を保証します。
## ようこそ
- NapCatQQ は NTQQ をベースにした最新の Bot プロトコル側実装です
## 特徴
- **簡単に使える**
- 初心者でも簡単に使用できます.
- **高速で効率的**
- 低メモリ環境のOSで長時間稼働できます.
- **豊富な API インターフェース**
- ほとんどの標準インターフェースを完全に実装しています.
- **安定して信頼できる**
- 継続的で安定した開発とメンテナンスを行っています.
## クイックスタート
最新バージョンは [Release](https://github.com/NapNeko/NapCatQQ/releases/) ページからダウンロードできます
**初めてご使用の方**は、以下のドキュメントで使用ガイドを必ずご確認ください
> このプロジェクトは非営利です。連携に関する問題/基本的な問題/下位フレームワークの問題については、ご自身で検索して解決してください。本プロジェクトのコミュニティではそのような回答は提供していません。
## リンク
| ドキュメント | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| ドキュメント | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 他のコミュニティでこのプロジェクト(他のプロトコル側/関連アプリケーション側のプロジェクトを含む)に言及して論争を引き起こさないでください。提案がある場合は、公式交流グループで議論するか、PRを提出してください。
## 謝辞
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 本プロジェクトへの多大なサポート、一部コードを参考にしています(許可済み)
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 本プロジェクトに完璧に対応した LLM Bot フレームワークです
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) サイバー仲間の 麦麦 Bot フレームワークです
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) NapCat ベースのメッセージエクスポートツールです
- そして何より大切なのは、画面の前のあなたに感謝することです~
---
## ライセンス
本プロジェクトはハイブリッドライセンスの下でオープンソース化されています。本プロジェクトを使用する際は、以下の点にご注意ください:
1. サードパーティライブラリのコードまたは修正部分は、元のオープンソースライセンスに従います.
2. 本プロジェクトは一部のプロジェクトから許可を得ており、一部の制約を受けません.
3. プロジェクトのその他のロジックコードは[本リポジトリのオープンソースライセンス](../LICENSE)に従います.
**本リポジトリは使いやすさの향上とメッセージプッシュ機能の実装のみを目的としています。また、リポジトリの主要作者の事前許可なく NapCat のコードに基づいてプロジェクトを開発することは禁止されています。使用する際は現地の法律と規制を遵守してください。これに起因する問題は、使用者および違反使用チュートリアルの提供者の責任となります。**
-77
View File
@@ -1,77 +0,0 @@
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
<div align="center">
# NapCat
_NTQQ 기반으로 구현된 최신 프로토콜 사이드 프레임워크._
> 구름이 일고 바람이 불어, 마음은 먼 곳을 향하나 길은 아직 닿지 못했네.
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | 한국어 | [Русский](./README_ru.md) | [العربية](./README_ar.md)
</div>
---
## 공지
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요. 이 기간 동안 공개 커뮤니티 그룹은 만들어지지 않지만, NapCat은 정기적인 업데이트를 보장합니다.
## 환영합니다
- NapCatQQ는 NTQQ를 기반으로 한 최신 Bot 프로토콜 구현체입니다
## 특징
- **사용하기 쉬움**
- 초보자도 쉽게 사용할 수 있습니다.
- **빠르고 효율적**
- 저메모리 시스템에서도 장시간 안정적으로 실행됩니다.
- **풍부한 API 인터페이스**
- 대부분의 표준 인터페이스를 완전히 구현했습니다.
- **안정적이고 신뢰할 수 있음**
- 지속적이고 안정적인 개발과 유지보수를 하고 있습니다.
## 빠른 시작
[Release](https://github.com/NapNeko/NapCatQQ/releases/) 페이지에서 최신 버전을 다운로드할 수 있습니다
**처음 사용하시는 분**은 아래 문서에서 사용 가이드를 반드시 확인해 주세요
> 이 프로젝트는 비영리입니다. 연동 문제/기본 문제/하위 프레임워크 문제는 직접 검색하여 해결해 주세요. 본 프로젝트 커뮤니티에서는 이러한 지원을 제공하지 않습니다.
## 링크
| 문서 | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| 문서 | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 다른 커뮤니티에서 이 프로젝트(다른 프로토콜 측/관련 애플리케이션 측 프로젝트 포함)를 언급하여 논쟁을 일으키지 마세요. 제안이 있으시면 공식 그룹에서 토론하거나 PR을 제출해 주세요.
## 감사의 말
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — 본 프로젝트에 대한 큰 지원, 일부 코드 참고 (허가 완료)
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — 본 프로젝트와 완벽하게 호환되는 LLM Bot 프레임워크
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — 사이버 친구 麦麦 Bot 프레임워크
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — NapCat 기반의 메시지 내보내기 도구
- 그리고 가장 중요한 것은, 지금 이 글을 읽고 있는 당신에게 감사드립니다~
---
## 라이선스
이 프로젝트는 하이브리드 라이선스로 오픈소스화되어 있습니다. 이 프로젝트를 사용할 때 다음 사항에 유의해 주세요:
1. 서드파티 라이브러리 코드 또는 수정된 부분은 원래의 오픈소스 라이선스를 따릅니다.
2. 이 프로젝트는 일부 프로젝트로부터 허가를 받아 일부 제한을 받지 않습니다.
3. 프로젝트의 나머지 로직 코드는 [본 리포지토리 라이선스](../LICENSE)를 따릅니다.
**이 리포지토리는 사용 편의성 향상과 메시지 푸시 기능 구현만을 목적으로 합니다. 또한, 리포지토리 주요 작성자의 사전 승인 없이 NapCat 코드를 기반으로 프로젝트를 개발하는 것은 금지되어 있습니다. 사용 시 현지 법률 및 규정을 준수해 주세요. 이로 인해 발생하는 문제는 사용자 및 위반 사용 튜토리얼 제공자의 책임입니다.**
-77
View File
@@ -1,77 +0,0 @@
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
<div align="center">
# NapCat
_Современный фреймворк на стороне протокола, реализованный на базе NTQQ._
> Облака поднимаются, ветер рождается, сердце стремится вдаль, но путь ещё не пройден.
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | Русский | [العربية](./README_ar.md)
</div>
---
## Объявление
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com. В этот период публичные группы сообщества создаваться не будут, но NapCat гарантирует регулярные обновления.
## Добро пожаловать
- NapCatQQ — это современная реализация протокола Bot на базе NTQQ
## Особенности
- **Простота использования**
- Начинающие пользователи смогут легко освоить работу.
- **Скорость и эффективность**
- Длительная работа на системах с ограниченным объёмом памяти.
- **Богатый API-интерфейс**
- Полная реализация большинства стандартных интерфейсов.
- **Стабильность и надёжность**
- Постоянная стабильная разработка и поддержка.
## Быстрый старт
Скачайте последнюю версию на странице [Release](https://github.com/NapNeko/NapCatQQ/releases/)
**При первом использовании** обязательно ознакомьтесь с руководством в документации ниже
> Проект является некоммерческим. Вопросы интеграции, базовые вопросы и вопросы по нижележащему фреймворку решайте самостоятельно — сообщество данного проекта не предоставляет такой поддержки.
## Ссылки
| Документация | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| Документация | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> Пожалуйста, не упоминайте данный проект (включая другие протокольные/прикладные проекты) в других сообществах во избежание споров. Если у вас есть предложения, обсуждайте их в официальной группе или отправляйте PR.
## Благодарности
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — большая поддержка данного проекта, частично использован код (с разрешения)
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — фреймворк LLM Bot, идеально совместимый с данным проектом
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — кибер-друг 麦麦, Bot-фреймворк
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — инструмент экспорта сообщений на базе NapCat
- И самое главное — спасибо вам, читающему это~
---
## Лицензия
Данный проект распространяется с открытым исходным кодом под гибридной лицензией. При использовании данного проекта обратите внимание на следующее:
1. Код сторонних библиотек или модифицированные части подчиняются их исходным лицензиям с открытым исходным кодом.
2. Данный проект получил разрешение от ряда проектов и не подчиняется некоторым ограничениям.
3. Остальной логический код проекта распространяется по [лицензии данного репозитория](../LICENSE).
**Данный репозиторий предназначен исключительно для повышения удобства использования и реализации функций отправки сообщений. Кроме того, запрещается разработка проектов на основе кода NapCat без предварительного разрешения главного автора репозитория. При использовании соблюдайте местное законодательство. За любые проблемы, вызванные нарушением, несут ответственность пользователь и лицо, предоставившее инструкции по незаконному использованию.**
-77
View File
@@ -1,77 +0,0 @@
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
<div align="center">
# NapCat
_基于 NTQQ 实现的现代化协议端框架._
> 云起兮风生,心向远方兮路未曾至.
[English](../README.md) | 简体中文 | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
</div>
---
## 公告
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com ,在此期不会建立任何公开社区交流群,Napcat会保证此期间的正常更新。
## 欢迎
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
## 特性
- **易于使用**
- 作为初学者能够轻松使用.
- **快速高效**
- 在低内存操作系统长时运行.
- **丰富的 API 接口**
- 完整实现了大部分标准接口.
- **稳定可靠**
- 持续稳定的开发与维护.
## 快速开始
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
**首次使用**请务必查看如下文档看使用教程
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
## 链接
| 文档 | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| 文档 | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
## 致谢
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
- 不过最最重要的 还是需要感谢屏幕前的你哦~
---
## 许可证
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
1. 第三方库代码或修改部分遵循其原始开源许可.
2. 本项目获取部分项目授权而不受部分约束
2. 项目其余逻辑代码采用[本仓库开源许可](../LICENSE).
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
-77
View File
@@ -1,77 +0,0 @@
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
<div align="center">
# NapCat
_基於 NTQQ 實現的現代化協議端框架._
> 雲起兮風生,心向遠方兮路未曾至.
[English](../README.md) | [简体中文](./README_zh-CN.md) | 繁體中文 | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
</div>
---
## 公告
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。在此期間不會建立任何公開社群交流群,NapCat 會保證此期間的正常更新。
## 歡迎
- NapCatQQ 是現代化的基於 NTQQ 的 Bot 協議端實現
## 特性
- **易於使用**
- 初學者也能輕鬆上手.
- **快速高效**
- 在低記憶體系統長時間穩定運行.
- **豐富的 API 介面**
- 完整實現了大部分標準介面.
- **穩定可靠**
- 持續穩定的開發與維護.
## 快速開始
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 頁面下載最新版本
**首次使用**請務必查看以下文件中的使用教學
> 專案為非營利性質,涉及 對接問題/基礎問題/底層框架問題 請自行搜尋解決,本專案社群不提供此類解答。
## 連結
| 文件 | [![Github.IO](https://img.shields.io/badge/docs%20on-Github.IO-orange)](https://napneko.github.io/) | [![Cloudflare.Worker](https://img.shields.io/badge/docs%20on-Cloudflare.Worker-black)](https://doc.napneko.icu/) | [![Cloudflare.HKServer](https://img.shields.io/badge/docs%20on-Cloudflare.HKServer-informational)](https://napcat.napneko.icu/) |
|:-:|:-:|:-:|:-:|
| 文件 | [![Cloudflare.Pages](https://img.shields.io/badge/docs%20on-Cloudflare.Pages-blue)](https://napneko.pages.dev/) | [![Server.Other](https://img.shields.io/badge/docs%20on-Server.Other-green)](https://napcat.top/) | [![NapCat.Top](https://img.shields.io/badge/docs%20on-NapCat.Top-red)](https://napcat.top/) |
|:-:|:-:|:-:|:-:|
| DeepWiki | [![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/NapNeko/NapCatQQ) |
|:-:|:-:|
> 請不要在其他社群提及本專案(包括其他協議端/相關應用端專案)以免引發爭論。如有建議,請到官方交流群討論或提交 PR。
## 致謝
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 對本專案的大力支持,參考部分程式碼(已獲授權)
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美適配本專案的 LLM Bot 框架,在此推薦
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一隻賽博群友 麥麥 Bot 框架,在此推薦
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基於 NapCat 的訊息匯出工具,在此推薦
- 不過最最重要的,還是要感謝螢幕前的你哦~
---
## 授權條款
本專案採用混合協議開源,因此使用本專案時,您需要注意以下幾點:
1. 第三方函式庫程式碼或修改部分遵循其原始開源授權.
2. 本專案已獲取部分專案授權而不受部分約束.
3. 專案其餘邏輯程式碼採用[本倉庫開源授權](../LICENSE).
**本倉庫僅用於提高易用性,實現訊息推送類功能,此外,禁止任何專案未經倉庫主作者授權基於 NapCat 程式碼開發。使用請遵守當地法律法規,由此造成的問題由使用者和提供違規使用教學者負責。**
-1
View File
@@ -16,7 +16,6 @@
}
},
"dependencies": {
"ajv": "^8.13.0",
"file-type": "^21.0.0"
},
"devDependencies": {
+30 -30
View File
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
proxy?: string;
}
type Uri2LocalRes = {
export type Uri2LocalRes = {
success: boolean,
errMsg: string,
fileName: string,
path: string;
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
};
// 定义一个异步函数来检查文件是否存在
@@ -151,7 +152,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 +166,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 +180,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 +188,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 +210,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 +233,7 @@ function httpDownloadWithProxy (url: string, headers: Record<string, string>, pr
redirectLocation = value;
}
}
bodyData = responseData.subarray(headerEndIndex + 4);
}
} else {
@@ -243,18 +244,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 +283,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 +305,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);
}
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
case FileUriType.Local: {
const fileExt = path.extname(HandledUri);
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
const tempFilePath = path.join(dir, filename + fileExt);
fs.copyFileSync(HandledUri, tempFilePath);
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
// 直接返回原始路径,不复制,避免不必要的 IO
return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
}
case FileUriType.Remote: {
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
fs.writeFileSync(filePath, buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
}
case FileUriType.Base64: {
const base64 = HandledUri.replace(/^base64:\/\//, '');
const base64Buffer = Buffer.from(base64, 'base64');
fs.writeFileSync(filePath, base64Buffer);
return { success: true, errMsg: '', fileName: filename, path: filePath };
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
}
default:
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '', isLocal: false };
}
}
-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
);
}
+22 -6
View File
@@ -24,12 +24,28 @@ export class NTQQGroupApi {
core: NapCatCore;
groupMemberCache: Map<string, Map<string, GroupMember>> = new Map<string, Map<string, GroupMember>>();
essenceLRU = new LimitedHashTable<number, string>(1000);
// psKey 滑动缓存,TTL 60 秒,惰性删除(不主动清理,等下次访问检测到过期再刷新)
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
constructor (context: InstanceContext, core: NapCatCore) {
this.context = context;
this.core = core;
}
/** 获取 qun.qq.com 域名的 psKey,滑动 TTL 60 秒(每次访问顺延) */
private async getQunPskey (): Promise<string> {
const now = Date.now();
if (this._qunPskeyCache && this._qunPskeyCache.expireAt > now) {
// 滑动 TTL:每次访问都顺延过期时间
this._qunPskeyCache.expireAt = now + 60 * 1000;
return this._qunPskeyCache.value;
}
// 过期或为空,惰性删除旧值(直接覆盖)并重新获取
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
this._qunPskeyCache = { value: psKey, expireAt: now + 60 * 1000 };
return psKey;
}
async setGroupRemark (groupCode: string, remark: string) {
return this.context.session.getGroupService().modifyGroupRemark(groupCode, remark);
}
@@ -75,7 +91,7 @@ export class NTQQGroupApi {
}
async fetchGroupEssenceList (groupCode: string) {
const pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const pskey = await this.getQunPskey();
return this.context.session.getGroupService().fetchGroupEssenceList({
groupCode,
pageStart: 0,
@@ -319,7 +335,7 @@ export class NTQQGroupApi {
}
async deleteGroupBulletin (groupCode: string, noticeId: string) {
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const psKey = await this.getQunPskey();
return this.context.session.getGroupService().deleteGroupBulletin(groupCode, psKey, noticeId);
}
@@ -423,7 +439,7 @@ export class NTQQGroupApi {
}
async uploadGroupBulletinPic (groupCode: string, imageurl: string) {
const _Pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
const _Pskey = await this.getQunPskey();
return this.context.session.getGroupService().uploadGroupBulletinPic(groupCode, _Pskey, imageurl);
}
@@ -466,8 +482,8 @@ export class NTQQGroupApi {
return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
}
async setGroupName (groupCode: string, groupName: string) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
async setGroupName (groupCode: string, groupName: string, isNormalMember: boolean = false) {
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, isNormalMember);
}
async publishGroupBulletin (groupCode: string, content: string, picInfo: {
@@ -475,7 +491,7 @@ export class NTQQGroupApi {
width: number,
height: number;
} | undefined = undefined, pinned: number = 0, confirmRequired: number = 0) {
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com');
const psKey = await this.getQunPskey();
// text是content内容url编码
const data = {
text: encodeURI(content),
+1 -1
View File
@@ -114,7 +114,7 @@ export class NTQQOnlineApi {
fileElement: {
fileName: actualFolderName,
filePath: folderPath,
fileSize: "",
fileSize: '',
},
};
+17 -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,14 @@ export class NTQQWebApi {
return (hash & 0x7FFFFFFF).toString();
}
async getAlbumListByNTQQ (gc: string) {
public getBknFromPSKey (psKey: string) {
return this.getBknFromSKey(psKey);
}
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 +479,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 +513,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,
+40
View File
@@ -534,5 +534,45 @@
"9.9.27-45758": {
"appid": 537340213,
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
},
"3.2.26-46494": {
"appid": 537345891,
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
},
"9.9.28-46494": {
"appid": 537345855,
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
},
"6.9.90-46494": {
"appid": 537345879,
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
},
"3.2.26-46928": {
"appid": 537345994,
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
},
"9.9.28-46928": {
"appid": 537345957,
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
},
"3.2.27-47354": {
"appid": 537346908,
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
},
"9.9.29-47354": {
"appid": 537346872,
"qua": "V1_WIN_NQ_9.9.29_47354_GW_B"
},
"6.9.93-47354": {
"appid": 537346896,
"qua": "V1_MAC_NQ_6.9.93_47354_GW_B"
},
"9.9.30-48517": {
"appid": 537352474,
"qua": "V1_WIN_NQ_9.9.30_48517_GW_B"
},
"3.2.28-48517": {
"appid": 537352510,
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
}
}
+56
View File
@@ -178,5 +178,61 @@
"9.9.27-45758-x64": {
"send": "0A6A6BC",
"recv": "1E87EC1"
},
"9.9.28-46494-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.26-46494-x64": {
"send": "5D30910",
"recv": "31814B0"
},
"3.2.26-46494-arm64": {
"send": "3EDC654",
"recv": "14A3124"
},
"3.2.26-46928-x64": {
"send": "5D30910",
"recv": "31814B0"
},
"3.2.26-46928-arm64": {
"send": "3EDC654",
"recv": "14A3124"
},
"9.9.28-46928-x64": {
"send": "0A6D66C",
"recv": "1E9890D"
},
"3.2.27-47354-x64": {
"send": "5D38930",
"recv": "318D090"
},
"3.2.27-47354-arm64": {
"send": "3EE8B24",
"recv": "14D422C"
},
"9.9.29-47354-x64": {
"send": "0A70B3C",
"recv": "1EAFD51"
},
"6.9.93-47354-arm64": {
"send": "244066C",
"recv": "09BCCF8"
},
"6.9.93-47354-x64": {
"send": "28ADE46",
"recv": "0A8FD5A"
},
"9.9.30-48517-x64": {
"send": "0A9B1BC",
"recv": "1F0324D"
},
"3.2.28-48517-x64": {
"send": "5E41890",
"recv": "3216D10"
},
"3.2.28-48517-arm64": {
"send": "3F9C7E4",
"recv": "14E1AA8"
}
}
+56
View File
@@ -686,5 +686,61 @@
"3.2.25-45758-arm64": {
"send": "6D6F9A0",
"recv": "6D73350"
},
"3.2.26-46494-x64": {
"send": "AB341C0",
"recv": "AB37C60"
},
"9.9.28-46494-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.26-46494-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
},
"3.2.26-46928-arm64": {
"send": "6DBBBB0",
"recv": "6DBF560"
},
"3.2.26-46928-x64": {
"send": "AB341C0",
"recv": "AB37C60"
},
"9.9.28-46928-x64": {
"send": "2E77C20",
"recv": "2E7B1A0"
},
"3.2.27-47354-x64": {
"send": "AB6A6C0",
"recv": "AB6E160"
},
"3.2.27-47354-arm64": {
"send": "6DE1438",
"recv": "6DE4DE8"
},
"9.9.29-47354-x64": {
"send": "2E84920",
"recv": "2E87EA0"
},
"6.9.93-47354-arm64": {
"send": "3FD1E98",
"recv": "3FD47A8"
},
"6.9.93-47354-x64": {
"send": "47CD940",
"recv": "47D04F0"
},
"3.2.28-48517-x64": {
"send": "AD7C280",
"recv": "AD7FD20"
},
"9.9.30-48517-x64": {
"send": "2F3B960",
"recv": "2F3EEE0"
},
"3.2.28-48517-arm64": {
"send": "6F48B70",
"recv": "6F4C520"
}
}
+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) {
+7 -6
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 { Type, Static, TSchema } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
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);
}
}
@@ -101,7 +101,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
// 获取文件大小和类型
const [fileType, duration] = await Promise.all([
fileTypeFromFile(videoPath).catch(() => null),
this.getDuration(videoPath),
this.getDuration(videoPath).catch(() => 60),
]);
// 创建临时缩略图路径
@@ -136,22 +136,24 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
}
/**
* 获取时长
*/
async getDuration (filePath: string): Promise<number> {
try {
const { stdout } = await execFileAsync(this.ffprobePath, [
'-v', 'error',
'-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1',
filePath,
]);
* 获取时长
*/
async getDuration(filePath: string): Promise<number> {
const { stdout } = await execFileAsync(this.ffprobePath, [
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
filePath,
]);
const duration = parseFloat(stdout.trim());
return isNaN(duration) ? 60 : duration;
} catch {
return 60; // 默认时长
const duration = parseFloat(stdout.trim());
if (isNaN(duration)) {
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
}
return duration;
}
/**
@@ -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
);
}
}
+32 -22
View File
@@ -59,13 +59,17 @@ class Subscription {
export const logSubscription = new Subscription();
export class LogWrapper implements ILogWrapper {
fileLogEnabled = true;
fileLogEnabled = false;
consoleLogEnabled = true;
logger: winston.Logger;
private logPath: string;
private fileTransportAdded = false;
private fileLogLevel: string = LogLevel.DEBUG;
constructor (logDir: string) {
const filename = `${getFormattedTimestamp()}.log`;
const logPath = path.join(logDir, filename);
this.logPath = path.join(logDir, filename);
this.logger = winston.createLogger({
level: 'debug',
@@ -77,12 +81,6 @@ export class LogWrapper implements ILogWrapper {
})
),
transports: [
new transports.File({
filename: logPath,
level: 'debug',
maxsize: 5 * 1024 * 1024, // 5MB
maxFiles: 5,
}),
new transports.Console({
format: format.combine(
format.colorize(),
@@ -107,7 +105,7 @@ export class LogWrapper implements ILogWrapper {
this.deleteOldLogFile(filePath, oneWeekAgo);
});
}).catch((err) => {
this.logger.error('Failed to read log directory', err);
this.logError('Failed to read log directory', err);
});
}
@@ -117,21 +115,22 @@ export class LogWrapper implements ILogWrapper {
fs.unlink(filePath).catch((err) => {
if (err) {
if (err.code === 'ENOENT') {
this.logger.warn(`File already deleted: ${filePath}`);
this.logWarn(`File already deleted: ${filePath}`);
} else {
this.logger.error('Failed to delete old log file', err);
this.logError('Failed to delete old log file', err);
}
} else {
this.logger.info(`Deleted old log file: ${filePath}`);
this.log(`Deleted old log file: ${filePath}`);
}
});
}
}).catch((err) => {
this.logger.error('Failed to get file stats', err);
this.logError('Failed to get file stats', err);
});
}
setFileAndConsoleLogLevel (fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
this.fileLogLevel = fileLogLevel;
this.logger.transports.forEach((transport) => {
if (transport instanceof transports.File) {
transport.level = fileLogLevel;
@@ -148,6 +147,15 @@ export class LogWrapper implements ILogWrapper {
setFileLogEnabled (isEnabled: boolean) {
this.fileLogEnabled = isEnabled;
if (isEnabled && !this.fileTransportAdded) {
this.fileTransportAdded = true;
this.logger.add(new transports.File({
filename: this.logPath,
level: this.fileLogLevel,
maxsize: 5 * 1024 * 1024, // 5MB
maxFiles: 5,
}));
}
this.logger.transports.forEach((transport) => {
if (transport instanceof transports.File) {
transport.silent = !isEnabled;
@@ -178,16 +186,18 @@ export class LogWrapper implements ILogWrapper {
}
_log (level: LogLevel, ...args: any[]) {
const message = this.formatMsg(args);
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
if (this.consoleLogEnabled || this.fileLogEnabled) {
const message = this.formatMsg(args);
if (this.consoleLogEnabled && this.fileLogEnabled) {
this.logger.log(level, message);
} else if (this.consoleLogEnabled) {
this.logger.log(level, message);
} else if (this.fileLogEnabled) {
// eslint-disable-next-line no-control-regex
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
}
logSubscription.notify(JSON.stringify({ level, message }));
}
logSubscription.notify(JSON.stringify({ level, message }));
}
log (...args: any[]) {
@@ -0,0 +1,34 @@
/**
* 服务器时间矫正 - 全局 Hook
*
* 保留 Date.now 原始引用,启动后通过 getServerTime 计算偏移量,
* 直接覆盖 Date.now(),使全局所有调用自动获得矫正后的时间戳。
*/
/** 原始 Date.now 引用,不受 hook 影响 */
export const OriginalDateNow: () => number = Date.now.bind(Date);
/**
* 初始化全局时间矫正,覆盖 Date.now()
* @param getServerTimeFn 获取服务器时间的函数,返回毫秒级时间戳字符串
* @returns 偏移量(毫秒)
*/
export function hookGlobalDateNow (getServerTimeFn: () => string): number {
const start = OriginalDateNow();
const serverTimeStr = getServerTimeFn();
const end = OriginalDateNow();
const serverTimeMs = parseInt(serverTimeStr, 10);
if (isNaN(serverTimeMs) || serverTimeMs <= 0) {
return 0;
}
// 补偿网络延迟:假定往返时间对称,服务器时间对应本地时间的中点 (start + end) / 2
const offsetMs = Math.round(serverTimeMs - (start + end) / 2);
if (Math.abs(offsetMs) > 5000) {
Date.now = () => OriginalDateNow() + offsetMs;
}
return offsetMs;
}
+6 -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 {
+24
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,28 @@ 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 {
const doTimeSync = () => {
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);
}
};
doTimeSync();
// 每小时定期重同步,防止长时间运行后本地时钟漂移触发风控
const syncTimer = setInterval(doTimeSync, 3600000);
syncTimer.unref();
}
// 遍历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"
@@ -41,6 +41,16 @@ export class PacketOperationContext {
await this.context.client.sendOidbPacket(req, true);
}
async CompleteGroupTodo (groupUin: number, msgSeq: string) {
const req = trans.CompleteGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async CancelGroupTodo (groupUin: number, msgSeq: string) {
const req = trans.CancelGroupTodo.build(groupUin, msgSeq);
await this.context.client.sendOidbPacket(req, true);
}
async FetchRkey (timeout: number = 10000) {
const req = trans.FetchRkey.build();
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
@@ -228,15 +238,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 +324,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')),
]),
},
}];
@@ -0,0 +1,20 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class CancelGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
return OidbBase.build(0xF90, 3, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new CancelGroupTodo();
@@ -0,0 +1,20 @@
import * as proto from '@/napcat-core/packet/transformer/proto';
import { NapProtoMsg } from 'napcat-protobuf';
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class CompleteGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
return OidbBase.build(0xF90, 2, data);
}
parse (data: Buffer) {
return OidbBase.parse(data);
}
}
export default new CompleteGroupTodo();
@@ -5,7 +5,7 @@ import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
class SetGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
build (peer: number, msgSeq: string): OidbPacket {
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90_1).encode({
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
groupUin: peer,
msgSeq: BigInt(msgSeq),
});
@@ -8,4 +8,6 @@ export { default as SetSpecialTitle } from './SetSpecialTitle';
export { default as ImageOCR } from './ImageOCR';
export { default as MoveGroupFile } from './MoveGroupFile';
export { default as RenameGroupFile } from './RenameGroupFile';
export { default as CompleteGroupTodo } from './CompleteGroupTodo';
export { default as CancelGroupTodo } from './CancelGroupTodo';
export { default as SetGroupTodo } from './SetGroupTodo';
@@ -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';
@@ -31,4 +31,4 @@ export * from './oidb/Oidb.0xED3_1';
export * from './oidb/Oidb.0XFE1_2';
export * from './oidb/OidbBase';
export * from './oidb/Oidb.0xE07';
export * from './oidb/Oidb.0xf90_1';
export * from './oidb/Oidb.0xf90';
@@ -1,6 +1,6 @@
import { ProtoField, ScalarType } from 'napcat-protobuf';
export const OidbSvcTrpcTcp0XF90_1 = {
export const OidbSvcTrpcTcp0XF90 = {
groupUin: ProtoField(1, ScalarType.UINT32),
msgSeq: ProtoField(2, ScalarType.UINT64),
};
@@ -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>;
@@ -341,7 +341,7 @@ export interface NodeIKernelMsgService {
getFileThumbSavePath (arg1: string, arg2: number, arg3: boolean): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): unknown;
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): Promise<GeneralCallResult>;
setPttPlayedState (arg1: string, arg2: Peer, arg3: string): unknown;
@@ -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;
+4 -2
View File
@@ -67,8 +67,10 @@ export function decryptDatabase (fileData: Buffer, passphrase: Buffer): Buffer |
decrypted.copy(output, 16);
// 修正 page_size 字段 (offset 16-17, big-endian)
output.writeUInt16BE(PAGE_SIZE, 16);
// 清零 reserved space 标志 (offset 20)
output[20] = 0;
// 保留原始 reserved-bytes-per-page 值 (byte 20)
// NTQQ SQLCipher 使用 reserved=80 用于 B-tree 布局 (usable=4016)
// 即使加密保留区 (IV+HMAC) 实际只有 48 字节
// 清零会导致 SQLite 误判溢出指针,报 "database disk image is malformed"
offset = PAGE_SIZE;
} else {
decrypted.copy(output, offset);
-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 () {
-19
View File
@@ -1,19 +0,0 @@
// LiteLoader需要提供部分IPC接口,以便于其他插件调用
const { ipcMain, BrowserWindow } = require('electron');
const napcat = require('./napcat.cjs');
const { shell } = require('electron');
ipcMain.handle('napcat_get_webui', async () => {
return napcat.NCgetWebUiUrl();
});
ipcMain.on('open_external_url', (event, url) => {
shell.openExternal(url);
});
ipcMain.on('napcat_open_inner_url', (event, url) => {
const win = new BrowserWindow({
autoHideMenuBar: true,
});
win.loadURL(url);
win.webContents.setWindowOpenHandler(details => {
win.loadURL(details.url);
});
});
-29
View File
@@ -1,29 +0,0 @@
{
"manifest_version": 4,
"type": "extension",
"name": "NapCatQQ",
"slug": "NapCat.Framework",
"description": "高性能的 OneBot 11 协议实现",
"version": "0.0.1",
"icon": "./logo.png",
"authors": [
{
"name": "NapNeko",
"link": "https://github.com/NapNeko"
}
],
"repository": {
"repo": "NapNeko/NapCatQQ",
"branch": "main"
},
"platform": [
"win32",
"linux",
"darwin"
],
"injects": {
"renderer": "./renderer.js",
"main": "./liteloader.cjs",
"preload": "./preload.cjs"
}
}
+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;
-14
View File
@@ -1,14 +0,0 @@
const { contextBridge, ipcRenderer } = require('electron');
const napcat = {
getWebUiUrl: async () => {
return ipcRenderer.invoke('napcat_get_webui');
},
openExternalUrl: async (url) => {
ipcRenderer.send('open_external_url', url);
},
openInnerUrl: async (url) => {
ipcRenderer.send('napcat_open_inner_url', url);
},
};
// 在window对象下导出只读对象
contextBridge.exposeInMainWorld('napcat', napcat);
-41
View File
@@ -1,41 +0,0 @@
export const onSettingWindowCreated = async (view) => {
const webui = await window.napcat.getWebUiUrl();
view.innerHTML = `
<setting-section data-title="">
<setting-panel>
<setting-list data-direction="column">
<setting-item>
<setting-button data-type="primary" class="nc_openwebui">在QQ内打开配置页面</setting-button>
<setting-button data-type="primary" class="nc_openwebui_ex">在默认浏览器打开配置页面</setting-button>
</setting-item>
<setting-item>
<div>
<setting-text>WebUi远程地址可以点击下方复制哦~</setting-text>
<setting-text class="nc_webui">WebUi</setting-text>
</div>
</setting-item>
</setting-list>
</setting-panel>
</setting-section>
`;
view.querySelector('.nc_openwebui').addEventListener('click', () => {
window.napcat.openInnerUrl(webui);
});
view.querySelector('.nc_openwebui_ex').addEventListener('click', () => {
window.napcat.openExternalUrl(webui);
});
view.querySelector('.nc_webui').innerText = webui;
// 添加点击复制功能
view.querySelector('.nc_webui').addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(webui);
// eslint-disable-next-line no-undef
alert('WebUi URL 已复制到剪贴板');
} catch (err) {
console.error('复制到剪贴板失败: ', err);
}
});
};
-2
View File
@@ -24,10 +24,8 @@ const FrameworkBaseConfigPlugin: PluginOption[] = [
targets: [
{ src: '../napcat-napi-loader/', dest: 'dist', flatten: true },
{ src: '../napcat-native/', dest: 'dist/native', flatten: false },
{ src: './manifest.json', dest: 'dist' },
{ src: '../napcat-core/external/napcat.json', dest: 'dist/config/' },
{ src: '../napcat-webui-frontend/dist/', dest: 'dist/static/', flatten: false },
{ src: './liteloader.cjs', dest: 'dist' },
{ src: './napcat.cjs', dest: 'dist' },
{ src: './nativeLoader.cjs', dest: 'dist' },
{ src: './preload.cjs', dest: 'dist' },
+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: {
@@ -11,4 +11,12 @@ export const PacketActionsExamples = {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
CompleteGroupTodo: {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
CancelGroupTodo: {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
};
@@ -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> {
@@ -5,7 +5,7 @@ import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
attach_info: Type.String({ default: '', description: '附加信息(用于分页)' }),
attach_info: Type.Optional(Type.String({ default: '', description: '附加信息(用于分页)' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -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.Optional(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,7 +26,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
override returnExample = ExtendsActionsExamples.OCRImage.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
const { path, success, isLocal } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
if (!success) {
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
}
@@ -39,7 +39,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
}
return ret.result;
} finally {
fs.unlink(path, () => { });
if (!isLocal) fs.unlink(path, () => { });
}
}
throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
@@ -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;
Loaded 100 of 294 files, more files were not shown because too many files have changed in this diff. Show more