Compare commits

...
38 Commits
Author SHA1 Message Date
手瓜一十雪 b1b357347b Remove unused installedVersion prop from PluginStoreCard
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
The installedVersion prop was declared but not used in PluginStoreCard. This commit removes it to clean up the component's props.
2026-01-29 17:13:30 +08:00
手瓜一十雪 129d63f66e Add mirror management and selection UI
Introduces backend API and router for mirror management, including latency testing and custom mirror setting. Adds frontend components and controllers for mirror selection, speed testing, and integration into system info and plugin store pages, allowing users to select and test download/list mirrors interactively.
2026-01-29 17:11:59 +08:00
手瓜一十雪 699b46acbd Improve plugin status handling and dirname lookup
Enhanced setPluginStatus to support enabling/disabling plugins by both package name and dirname, improving robustness when plugins are not loaded. Also removed redundant directory name matching logic from findDirnameById in the web UI backend.

Register plugin after installation in PluginStore

Adds logic to immediately register a plugin with the plugin manager after installation, both in the standard and SSE install handlers. This ensures newly installed plugins are available without requiring a restart or manual reload.

Refactor plugin path handling in plugin manager

Simplifies plugin directory and data path resolution by using pluginPath from the plugin context instead of fileId. Streamlines plugin uninstall and reload logic, removing redundant file system scans and improving code clarity.

Refactor plugin API to use package id and improve UX

Standardized plugin management APIs and frontend to use 'id' (package name) instead of ambiguous 'name' or 'filename'. Added support for a 'plugin' display field in package.json and improved plugin store UI to show install/update status. Refactored backend and frontend logic for enabling, disabling, uninstalling, and configuring plugins to use consistent identifiers, and enhanced type definitions and documentation for better maintainability.
2026-01-29 16:42:15 +08:00
手瓜一十雪 7f05aee11d Add manual plugin manager registration support
Introduces backend and frontend logic to manually register the plugin manager if not already loaded. Adds a new API endpoint and frontend UI prompt to guide users through registration after plugin installation when necessary.
2026-01-29 15:44:26 +08:00
手瓜一十雪 542036f46e Refactor type build: inline external types, simplify scripts
Removed custom build scripts for copying and inlining types, consolidating all post-build logic into a single enhanced post-build.mjs script. The new script processes .d.ts files, inlines external module types, updates imports, and copies necessary files to dist, eliminating the need for external-shims and simplifying the build process. Updated package.json scripts accordingly.

Refactor type inlining: remove shims, auto-extract types

Removed external-shims.d.ts and its references, replacing manual shims with an automated script that extracts type definitions from node_modules. Updated build scripts, dependencies, and test files to support the new inlining process. The inline-types.mjs script now scans for external imports, generates inline type files, and rewrites imports as import type, eliminating the need for hand-written shims.

Add type inlining script and update build process

Introduced a new script (inline-types.mjs) to inline external type dependencies into the dist directory, updated the build process to use this script, and removed the now-unnecessary external-shims.d.ts from the copy-dist script. Added a test file to verify inlined types, updated dependencies to include ts-morph, and adjusted package.json and pnpm-lock.yaml accordingly.
2026-01-29 15:27:46 +08:00
pohgxz b958e9e803 修复 OpenAPI 导出的相应接口缺失 stream 字段 2026-01-29 14:14:11 +08:00
冷曦 73fcfb5900 修复下载插件后插件列表显示开启 (#1560)
下载后插件应该为禁用状态,但是前端显示启用状态
2026-01-29 13:12:54 +08:00
手瓜一十雪 adabc4da46 Improve schema parsing and error handling in API debug tools
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
Enhances the TypeBox schema parser to better handle deep nesting, circular references, and union truncation, and adds error handling for schema parsing and default value generation in the OneBot API debug UI. Updates the display component to show clear messages for circular or truncated schemas, and improves robustness in HTTP debug command execution. Also synchronizes the ParsedSchema type in the Zod utility for consistency.
2026-01-28 16:07:23 +08:00
手瓜一十雪 bf073b544b Refactor schema ID handling and reduce parse depth
Changed MAX_PARSE_DEPTH from 10 to 6 to limit nesting. Improved schema ID retrieval to only use $id if present, and added a utility to collect all $id values in a schema for better circular reference detection. Updated font file AaCute.woff.
2026-01-28 16:01:43 +08:00
手瓜一十雪 a71219062a Enhance TypeBox schema parsing with circular ref detection
Added detection and handling for circular references and excessive nesting in TypeBox schema parsing and default value generation. Introduced depth limits and a visited set to prevent infinite recursion, and updated the parseTypeBox and generateDefaultFromTypeBox functions accordingly.
2026-01-28 15:59:27 +08:00
手瓜一十雪 001fe01ace Add plugin logger interface and update builtin plugin
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
Introduces a PluginLogger interface and injects a plugin-specific logger into the plugin context for consistent logging. Refactors the builtin plugin to use the new logger instead of direct console calls. Updates napcat-types to version 0.0.9 in dependencies and lock files.
2026-01-28 15:07:06 +08:00
手瓜一十雪 0aa0c44634 Refactor plugin identification to use package name and dirname
Updated plugin manager and API to distinguish between plugin package name and directory name (dirname) for more robust plugin identification and path resolution. Adjusted context creation, status management, and API handlers to use package name for identification and dirname for filesystem operations. Also replaced console.error with console.log in builtin plugin for consistency.
2026-01-28 15:02:47 +08:00
手瓜一十雪 93126e514e Refactor builtin plugin for improved type safety
Replaced generic 'any' types with 'NetworkAdapterConfig' for better type safety in getVersionInfo and sendMessage functions. Removed redundant comments and improved code clarity. Changed a warning log to a standard log for config load failures.
2026-01-28 14:54:43 +08:00
手瓜一十雪 1ae10ae0c6 Refactor plugin to use context actions and update deps
Refactored the builtin plugin to pass actions and adapterName explicitly from context instead of relying on a global variable. Updated napcat-types dependency to version 0.0.8.
2026-01-28 14:42:44 +08:00
手瓜一十雪 4b693bf6e2 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:38:11 +08:00
手瓜一十雪 574c257591 Refactor plugin manager to support only directory plugins
Removed support for single-file plugins in OB11PluginMangerAdapter, simplifying plugin identification to use directory names as unique IDs. Updated related logic in the backend API to align with this change, ensuring consistent plugin management and status handling.
2026-01-28 14:18:44 +08:00
手瓜一十雪 d680328762 Add config UI and persistence to builtin plugin
Introduces a configuration UI schema and persistent config storage for the napcat-plugin-builtin. The plugin now loads and saves its configuration, supports dynamic prefix and reply toggling, and updates dependencies to napcat-types v0.0.6.
2026-01-28 14:13:48 +08:00
手瓜一十雪 d711cdecaf Add plugin config management to backend and frontend
Introduces a unified plugin configuration schema and API in the backend, with endpoints for getting and setting plugin config. Updates the frontend to support plugin config modals, including a UI for editing plugin settings. Also adds support for uninstalling plugins with optional data cleanup, and updates dependencies to use napcat-types@0.0.5.
2026-01-28 13:56:40 +08:00
手瓜一十雪 c5f1792009 Add plugin data management API and frontend support
Introduced backend API endpoints for managing plugin configuration data, including listing, reading, saving, and deleting plugin data files. Added a new PluginData API module and registered related routes. Updated the frontend plugin manager controller to support these new API methods and corresponding TypeScript interfaces. Also fixed minor typos in documentation prompts.
2026-01-28 13:39:36 +08:00
手瓜一十雪 a5e705e6a4 Fix typo in Windows deployment instructions
Corrected a grammatical error in the Windows one-click deployment section in both the default prompt and release note prompt files.
2026-01-27 23:01:16 +08:00
手瓜一十雪 007f1db339 Update OpenAPI schema copy path in release workflow
The workflow now copies openapi.json from the dist directory instead of the package root, ensuring the built schema is used during the release process.
2026-01-27 23:00:14 +08:00
手瓜一十雪 008fb39f8f Reduce WebSocket maxPayload to 50 MB
Lowered the maxPayload limit from 1 GB to 50 MB in both the WebSocket client and server adapters to improve resource management and prevent excessively large payloads.
2026-01-27 22:56:27 +08:00
手瓜一十雪 6b8cc6756d Add plugin install SSE API and mirror selection 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
Introduces a new SSE-based plugin installation API for real-time progress updates and adds frontend support for selecting download mirrors, especially for GitHub-based plugins. Refactors backend plugin directory handling, improves logging, and updates the frontend to use the new API with user-selectable mirrors and progress feedback.
2026-01-27 22:51:45 +08:00
手瓜一十雪 24623f18d8 Implement real plugin store backend and install logic
Replaces mock plugin store data with live fetching from a remote source using mirrors and caching. Implements actual plugin download, extraction, and installation logic in the backend. Updates frontend to call the new install API and display installation results, and removes unused icon/rating display from plugin cards.
2026-01-27 22:03:47 +08:00
手瓜一十雪 8b676ed693 Refactor plugin store types and update category logic
Simplified PluginStoreItem types by removing unused fields and standardizing the minimum version property. Updated frontend plugin store page to use new categories ('官方', '工具', '娱乐', '其它') instead of download-based sorting, aligning with the revised type definitions.
2026-01-27 21:47:44 +08:00
手瓜一十雪 ab2dfcfd8f Update dependencies in pnpm-lock.yaml
Added @sinclair/typebox to packages/napcat-types dependencies.
2026-01-27 21:31:31 +08:00
手瓜一十雪 2998e04435 Add @sinclair/typebox as dependency and remove shim
Removed the manual TypeBox type definitions from external-shims.d.ts and added @sinclair/typebox as a dependency in package.json and package.public.json. Bumped package version to 0.0.4 to reflect this change.
2026-01-27 21:24:50 +08:00
手瓜一十雪 613690f5af Fix build:openapi script to use sequential commands
Replaces '&' with '&&' in the build:openapi script to ensure that 'node ./dist/schemas.mjs' runs only after 'vite build' completes successfully.
2026-01-27 20:34:21 +08:00
手瓜一十雪 a60d8d109c Update napcat-types usage and config in plugin
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
Changed napcat-plugin-builtin to use workspace reference for napcat-types instead of a fixed version. Updated tsconfig to use bundler module resolution and improved Vite config plugin resolution. Enhanced napcat-types package.json exports for better type support.
2026-01-27 20:22:40 +08:00
时瑾 28c9761e3d fix(napcat-plugin-builtin): 修复vite.config.ts hook 2026-01-27 20:07:53 +08:00
手瓜一十雪 805cc32d7f Update napcat-types dependency to version 0.0.2
Changed import paths in index.ts to match new napcat-types structure and updated package.json to use napcat-types@0.0.2 instead of workspace reference. Updated pnpm-lock.yaml accordingly.
2026-01-27 19:12:04 +08:00
手瓜一十雪andpohgxz de9d5180fe Add payload and return schemas to OneBot actions (#1549)
* Add payload and return schemas to OneBot actions

Introduced explicit payloadSchema and returnSchema definitions for all OneBotAction classes using @sinclair/typebox. This improves type safety, API documentation, and validation for action payloads and return values. Also refactored method signatures and types for consistency across the codebase.

* Refactor payload schemas to use string IDs

Replaced Type.Union([Type.Number(), Type.String()]) with Type.String for group_id, user_id, and similar fields across all action payload schemas to standardize input types. Also made minor improvements to error handling, return types, and removed unused imports for better code clarity and consistency.

* Refactor type definitions and payload schemas in actions

Standardized type usage and improved type safety across multiple OneBot action files. Updated payload schemas to use string types for IDs and flags, refined return types, and enhanced message content typing. Added error handling for missing parameters in SetGroupTodo.

* Refactor type handling and improve message parsing

Updated several actions to use more precise type casting and type guards, improving type safety and clarity. Enhanced message parsing logic for forward messages and group/friend message history. Standardized return schemas and error handling for avatar and group portrait actions.

* Add napcat-schema package for OpenAPI generation

Introduces the napcat-schema package with scripts and configuration to auto-generate OpenAPI schemas for NapCat OneBot 11 actions. Refactors action handler export in napcat-onebot to support schema extraction.

* Add action examples and enhance action metadata

Introduced a centralized examples.ts file providing payload and return examples for all actions. Updated numerous action classes to include actionDescription, actionTags, payloadExample, and returnExample fields, improving API documentation and discoverability.

* Refactor action example imports and add example files

Moved action example data to dedicated 'examples.ts' files for each action category (extends, file, go-cqhttp, group, msg, system, user). Updated all action classes to import and use the new example modules, improving code organization and maintainability. Also added missing actionTags and actionDescription where appropriate.

* Update GetGroupMemberList.ts

* Add actionSummary and improve action metadata

Introduces the actionSummary property to OneBotAction and updates all action classes to provide concise summaries and improved descriptions. Refactors example imports for better modularity, adds new example files for guild and packet actions, and updates the OpenAPI schema generator to use the new summary and improved descriptions. This enhances API documentation clarity and consistency.

* Enhance action metadata and add examples for new actions

Added actionSummary, actionDescription, and actionTags to multiple OneBot actions for improved API documentation. Introduced payload and response examples for new actions (GetDoubtFriendsAddRequest, SetDoubtFriendsAddRequest) in a new examples.ts file. Also removed unused imports from several files for code clarity.

* Refactor action examples and enhance metadata

Replaced generic ActionExamples imports with more specific examples modules (FileActionsExamples, GroupActionsExamples, GoCQHTTPActionsExamples) across file, group, and go-cqhttp actions. Added or updated actionSummary, actionDescription, actionTags, payloadExample, and returnExample properties for improved API documentation and clarity.

* Refactor extends actions to use new examples module

Replaced imports of ActionExamples with ExtendsActionsExamples in all extends actions. Updated action summary, description, tags, and example references for consistency and clarity across actions. This improves maintainability and aligns with the new examples structure.

* Add action metadata to OneBot action classes

Added or updated actionSummary, actionTags, payloadExample, and returnExample properties for all OneBot action classes in the napcat-onebot package. This improves API documentation and discoverability by providing concise summaries, categorization tags, and usage examples for each action.

* Refactor OpenAPI schema generation to 3.0.1 format

Updated the OpenAPI schema output to use version 3.0.1, restructured tags, responses, and examples for better clarity and compatibility, and simplified output file locations. Also removed unused scripts from package.json.

* Fix SendPokePayloadSchema type definitions

Corrected the type definitions for user_id and target_id to only allow strings, and fixed a syntax error in group_id. This ensures payload validation is consistent and accurate.

Refactor fileset ID API response and schema handling

Updated GetFilesetId action to return a structured object with fileset_id and adjusted its return schema accordingly. Improved frontend TypeBox schema parsing to support allOf (intersection) merging and updated API debug component to construct response schemas in a more robust way for object recognition.

Refactor OneBot API schema handling to use TypeBox

Replaces Zod-based static API schema definitions with dynamic fetching of schemas from the backend using TypeBox. Removes legacy static schema files, updates frontend API debug components to use TypeBox utilities, and adds @sinclair/typebox as a dependency. Backend now exposes a /schemas endpoint for all OneBot actions. Various schema and description fields are updated for clarity and consistency.

* Remove OneBot API navigation list component

Deleted nav_list.tsx from the onebot/api components, removing the OneBotApiNavList React component and its related logic. This may be part of a refactor or cleanup to eliminate unused or redundant UI code.

* Add action tags to OneBot API schema and update tag name

Included the 'tags' property in the OneBot API schema for both backend and frontend, allowing actions to be categorized. Also updated the action tag from '群扩展' to '群组扩展' in SetGroupSign for consistency.

* Add napcat-types package for unified type exports

Introduced the napcat-types package to aggregate and re-export all types, enums, and classes from napcat-core and napcat-onebot. Added external module shims, test files, and configuration for type-only distribution. Updated core and onebot packages to improve export granularity and fixed import paths for better modularity.

* Move external-shims.d.ts to files in tsconfig

external-shims.d.ts was moved from the include array to the files array in tsconfig.json to ensure it is always included explicitly. This change clarifies the intent and may help with TypeScript's file resolution.

Refactor napcat-types package and update plugin deps

Refactored napcat-types to provide more accurate shims, added real type dependencies, and improved build/test scripts. Updated napcat-plugin and napcat-plugin-builtin to depend on napcat-types instead of napcat-onebot. Adjusted imports in affected packages to use napcat-types, and updated pnpm-lock.yaml accordingly.

Add build and test scripts to napcat-types package

Introduced 'build' and 'test' scripts in the napcat-types package.json for easier development and testing. Also updated dependencies in the lockfile.

* 完善部分api描述

* Remove unused statusText constant

Deleted the unused statusText constant from FetchCustomFace.ts to clean up the code.

* Bump napcat-types version to 0.0.2

Updated the package version in package.public.json from 0.0.1 to 0.0.2.

Update napcat-types package metadata and dependencies

Set package as public by changing 'private' to false. Move 'napcat-core' and 'napcat-onebot' from dependencies to devDependencies, and remove 'compressing' from dependencies.

Add public packaging and build script for napcat-types

Introduces package.public.json and a copy-dist.mjs script to automate copying metadata and README into the dist folder for publishing. Updates build script in package.json to use the new copy step. Adds initial package.json and README for napcat-types.

Update scripts in napcat-types package configs

Added a publish script to package.json and removed scripts from package.public.json to streamline configuration and avoid duplication.

* Update publish script to use npm in dist directory

Changed the publish script to run 'npm publish' from the 'dist' directory instead of using 'pnpm publish --filter napcat-types'. This ensures the published package uses the built output.

* Update pnpm-lock.yaml dependencies

Removed 'compressing' from dependencies and cleaned up libc fields for various platform-specific packages. This streamlines the lock file and may improve cross-platform compatibility.

* Add workflow to publish OpenAPI schema to NapCatDocs

Introduces a new 'publish-schema' job in the auto-release workflow. This job builds the napcat-schema package, copies the generated OpenAPI schema to the NapCatDocs repository under a versioned path, and commits the update. Automates schema publishing on release events.

* AI修正部分api文档

* Update OpenAPI version and use dynamic version from napcat-common

Changed OpenAPI spec version to 3.1.0 and replaced the hardcoded API version with napCatVersion from napcat-common. Added napcat-common as a dependency in package.json.

* Update napcat-schema build and OpenAPI version

Renamed the build script from build:schema to build:openapi in napcat-schema and updated the workflow to use the new script. Changed OpenAPI version from 3.1.0 to 3.0.1 in the schema generator. Added napcat-vite as a dependency and integrated its version plugin into the Vite config.

* 暂时OK

* Refactor action examples structure and imports

Moved action example files into a new 'example' directory and updated all imports accordingly. Removed the monolithic 'examples.ts' and redefined ActionExamples in OneBotAction.ts to only include common error codes. This improves code organization and maintainability.

* Fix type for rate limiter middleware in router

Casts the rate limiter middleware to RequestHandler to resolve type compatibility issues with Express router middleware.

* Add OB11 message segment schemas and update SendMsg

Introduces a comprehensive message segment schema (OB11) in a new file, refactors SendMsg payload to use the new OB11MessageMixTypeSchema, and updates related type definitions for improved type safety and extensibility in message handling.

* Refactor OB11 message types to use TypeBox schemas

Migrates all OB11 message segment and message type definitions from interface/enums to TypeBox schemas in types/message.ts. Removes the now-redundant message-segment-schema.ts file and updates imports to use the new schema-based types. This unifies type validation and TypeScript types, improving maintainability and consistency.

---------

Co-authored-by: pohgxz <Ttjonne@outlook.com>
2026-01-27 19:07:17 +08:00
手瓜一十雪 791e359199 Update documentation links in README
Replaced outdated Server.Other and NapCat.Wiki links with updated napcat.top URLs and labels in the documentation section of the README.
2026-01-27 12:59:18 +08:00
手瓜一十雪 63a9d571f3 Add flexible IP access control to WebUI config
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
Replaces the 'disableNonLANAccess' option with a more flexible access control system supporting 'none', 'whitelist', and 'blacklist' modes, along with IP list and X-Forwarded-For support. Updates backend API, config schema, middleware, and frontend UI to allow configuration of access control mode, IP whitelist/blacklist, and X-Forwarded-For handling. Removes legacy LAN-only access logic and updates types accordingly.
2026-01-26 19:46:15 +08:00
手瓜一十雪 59d4b08982 Fix typo in delBuddy method name & fix #1550
Renamed the delBuudy method to delBuddy in NTQQFriendApi and updated its usage in GoCQHTTPDeleteFriend to ensure correct method invocation.
2026-01-25 21:09:12 +08:00
手瓜一十雪 81e4e54f25 Optimize emoji likes fetching logic
Adjusts the pagination logic to fetch only the required number of pages based on the requested count. Trims the result list to the specified count if provided, improving efficiency and accuracy.
2026-01-25 13:21:27 +08:00
Hans155922and手瓜一十雪 b75b733bb0 增加/fetch_emoji_likes_all (#1548)
* Update FetchEmojiLike.ts

* 减少getMsgEmojiLikesList参数,一次性全部拉取

* Update FetchEmojiLike.ts

* Refactor API message schema and update descriptions

* Update and rename FetchEmojiLike.ts to FetchEmojiLikesAll.ts

* Create FetchEmojiLike.ts

* Update router.ts

* Update index.ts

* Update index.ts

* Update FetchEmojiLikesAll.ts

* Update FetchEmojiLikesAll.ts

* Refactor emoji likes API and update related logic

Replaces FetchEmojiLikesAll with GetEmojiLikes, updating the API to use a new payload and return schema. Adjusts action registration, router action names, and frontend API mapping accordingly. Adds isShortId utility to MessageUnique for improved message ID handling.

---------

Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-01-25 13:18:16 +08:00
H3CoF6and手瓜一十雪 246269b519 feat: Support custom filename and cover image for Flash Transfer (#1544)
* feat: support thumbnail for flash-transfer

* fix: fix get thumbnail path unknown type error

* Refactor flash module types and enums

Standardized TypeScript interface property formatting in flash.ts, flash data, and wrapper files. Introduced the UploadSceneType enum for upload scene types, replacing hardcoded numeric values. Improved type annotations and consistency across the flash API and related data structures.

* Update arg type in NodeQQNTWrapperUtil interface

Changed the type of the 'arg' parameter in the NodeQQNTWrapperUtil interface from optional number to 'number | null | undefined' for improved type clarity.

* Refactor flash scene type and update method params

Introduced BusiScene enum for sceneType in FileListInfoRequests to improve type safety. Renamed parameters in getFileThumbSavePathForSend for better clarity.

* Refactor downloadSceneType to use enum type

Replaced numeric downloadSceneType fields with the DownloadSceneType enum in relevant interfaces. Updated NodeIKernelFlashTransferService method signatures to use DownloadSceneType for download operations, improving type safety and code clarity.

* refactor: remove thumbnail dependency for QQ resource icons

* fix: remove useless console.log

---------

Co-authored-by: 手瓜一十雪 <nanaeonn@outlook.com>
2026-01-25 09:51:43 +08:00
261 changed files with 9960 additions and 5664 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+1 -1
View File
@@ -31,7 +31,7 @@
[使用文档](https://napneko.github.io/)
## Windows 一键包
我们为提供了的轻量化一键部署方案
我们提供了轻量化的一键部署方案
相对于普通需要安装QQ的方案,下面已内置QQ和Napcat 阅读使用文档参考
你可以下载
+57
View File
@@ -5,6 +5,63 @@ on:
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:
+1 -1
View File
@@ -50,7 +50,7 @@ _Modern protocol-side framework implemented based on NTQQ._
| 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/) |
|:-:|:-:|:-:|:-:|
| 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.cyou/) | [![NapCat.Wiki](https://img.shields.io/badge/docs%20on-NapCat.Wiki-red)](https://www.napcat.wiki) |
| 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 | [![QQ Group#4](https://img.shields.io/badge/QQ%20Group%234-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#3](https://img.shields.io/badge/QQ%20Group%233-Join-blue)](https://qm.qq.com/q/8zJMLjqy2Y) | [![QQ Group#2](https://img.shields.io/badge/QQ%20Group%232-Join-blue)](https://qm.qq.com/q/CMmPbGw0jA) | [![QQ Group#1](https://img.shields.io/badge/QQ%20Group%231-Join-blue)](https://qm.qq.com/q/I6LU87a0Yq) |
+9 -3
View File
@@ -58,12 +58,12 @@ export class LimitedHashTable<K, V> {
}
// 获取最近刚写入的几个值
getHeads (size: number): { key: K; value: V }[] | undefined {
getHeads (size: number): { key: K; value: V; }[] | undefined {
const keyList = this.getKeyList();
if (keyList.length === 0) {
return undefined;
}
const result: { key: K; value: V }[] = [];
const result: { key: K; value: V; }[] = [];
const listSize = Math.min(size, keyList.length);
for (let i = 0; i < listSize; i++) {
const key = keyList[listSize - i];
@@ -108,7 +108,7 @@ class MessageUniqueWrapper {
return shortId;
}
getMsgIdAndPeerByShortId (shortId: number): { MsgId: string; Peer: Peer } | undefined {
getMsgIdAndPeerByShortId (shortId: number): { MsgId: string; Peer: Peer; } | undefined {
const data = this.msgDataMap.getKey(shortId);
if (data) {
const [msgId, chatTypeStr, peerUid] = data.split('|');
@@ -136,6 +136,12 @@ class MessageUniqueWrapper {
this.msgIdMap.resize(maxSize);
this.msgDataMap.resize(maxSize);
}
isShortId (message_id: string): boolean {
const num = Number(message_id);
// 判断是否是整数并且在 INT32 的范围内
return Number.isInteger(num) && num >= -2147483648 && num <= 2147483647;
}
}
export const MessageUnique: MessageUniqueWrapper = new MessageUniqueWrapper();
+9 -21
View File
@@ -383,17 +383,14 @@ export async function testUrlHead (url: string, timeout: number = 5000): Promise
}, (res) => {
const statusCode = res.statusCode || 0;
const contentType = (res.headers['content-type'] as string) || '';
const contentLength = parseInt((res.headers['content-length'] as string) || '0', 10);
// 验证条件:
// 简化验证条件:
// 1. 状态码 2xx 或 3xx
// 2. Content-Type 不应该是 text/html(表示错误页面)
// 3. 对于 .zip 文件,Content-Length 应该 > 1MB(避免获取到错误页面)
const isValidStatus = statusCode >= 200 && statusCode < 400;
const isNotHtmlError = !contentType.includes('text/html');
const isValidSize = url.endsWith('.zip') ? contentLength > 1024 * 1024 : true;
resolve(isValidStatus && isNotHtmlError && isValidSize);
resolve(isValidStatus && isNotHtmlError);
});
req.on('error', () => resolve(false));
@@ -437,10 +434,9 @@ export async function validateUrl (url: string, timeout: number = 5000): Promise
const contentType = (res.headers['content-type'] as string) || '';
const contentLength = parseInt((res.headers['content-length'] as string) || '0', 10);
// 验证条件
// 简化验证条件
const isValidStatus = statusCode >= 200 && statusCode < 400;
const isNotHtmlError = !contentType.includes('text/html');
const isValidSize = url.endsWith('.zip') ? contentLength > 1024 * 1024 : true;
if (!isValidStatus) {
resolve({
@@ -458,14 +454,6 @@ export async function validateUrl (url: string, timeout: number = 5000): Promise
contentLength,
error: '返回了 HTML 页面而非文件',
});
} else if (!isValidSize) {
resolve({
valid: false,
statusCode,
contentType,
contentLength,
error: `文件过小 (${contentLength} bytes),可能是错误页面`,
});
} else {
resolve({
valid: true,
@@ -542,21 +530,21 @@ export async function findAvailableDownloadUrl (
const testWithValidation = async (url: string): Promise<boolean> => {
if (validateContent) {
const result = await validateUrl(url, timeout);
// 额外检查文件大小
// 额外检查文件大小(仅当指定了 minFileSize 时)
if (result.valid && minFileSize && result.contentLength && result.contentLength < minFileSize) {
return false;
}
return result.valid;
}
return testMethod === 'head' ? testUrlHead(url, timeout) : testUrl(url, timeout);
// 不验证内容,只检查状态码
const isValid = testMethod === 'head' ? await testUrlHead(url, timeout) : await testUrl(url, timeout);
return isValid;
};
// 1. 如果设置了自定义镜像,优先使用
// 1. 如果设置了自定义镜像,直接使用(不测试,信任用户选择)
if (customMirror) {
const customUrl = buildMirrorUrl(originalUrl, customMirror);
if (await testWithValidation(customUrl)) {
return customUrl;
}
return customUrl;
}
// 2. 先测试原始 URL
+61 -18
View File
@@ -4,6 +4,7 @@ import {
FileListResponse,
FlashFileSetInfo,
SendStatus,
UploadSceneType,
} from '@/napcat-core/data/flash';
import { Peer } from '@/napcat-core/types';
@@ -19,25 +20,44 @@ export class NTQQFlashApi {
/**
* 发起闪传上传任务
* @param fileListToUpload 上传文件绝对路径的列表,可以是文件夹!!
* @param thumbnailPath
* @param filesetName
*/
async createFlashTransferUploadTask (fileListToUpload: string[]): Promise < GeneralCallResult & {
async createFlashTransferUploadTask (fileListToUpload: string[], thumbnailPath: string, filesetName: string): Promise<GeneralCallResult & {
createFlashTransferResult: createFlashTransferResult;
seq: number;
} > {
}> {
const flashService = this.context.session.getFlashTransferService();
const timestamp : number = Date.now();
const timestamp: number = Date.now();
const selfInfo = this.core.selfInfo;
const fileUploadArg = {
screen: 1, // 1
name: filesetName,
uploaders: [{
uin: selfInfo.uin,
uid: selfInfo.uid,
sendEntrance: '',
nickname: selfInfo.nick,
}],
coverPath: thumbnailPath,
paths: fileListToUpload,
excludePaths: [],
expireLeftTime: 0,
isNeedDelDeviceInfo: false,
isNeedDelLocation: false,
coverOriginalInfos: [
{
path: fileListToUpload[0] || '',
thumbnailPath,
},
],
uploadSceneType: UploadSceneType.KUPLOADSCENEAIOFILESELECTOR, // 不知道怎么枚举 先硬编码吧 (PC QQ 10)
detectPrivacyInfoResult: {
exists: false,
allDetectResults: new Map(),
},
};
const uploadResult = await flashService.createFlashTransferUploadTask(timestamp, fileUploadArg);
@@ -54,9 +74,9 @@ export class NTQQFlashApi {
* 下载闪传文件集
* @param fileSetId
*/
async downloadFileSetBySetId (fileSetId: string): Promise < GeneralCallResult & {
extraInfo: unknown
} > {
async downloadFileSetBySetId (fileSetId: string): Promise<GeneralCallResult & {
extraInfo: unknown;
}> {
const flashService = this.context.session.getFlashTransferService();
const result = await flashService.startFileSetDownload(fileSetId, 1, { isIncludeCompressInnerFiles: false }); // 为了方便,暂时硬编码
@@ -72,7 +92,7 @@ export class NTQQFlashApi {
* 获取闪传的外链分享
* @param fileSetId
*/
async getShareLinkBySetId (fileSetId: string): Promise < GeneralCallResult & {
async getShareLinkBySetId (fileSetId: string): Promise<GeneralCallResult & {
shareLink: string;
expireTimestamp: string;
}> {
@@ -91,9 +111,9 @@ export class NTQQFlashApi {
* 从分享外链获取文件集id
* @param shareCode
*/
async fromShareLinkFindSetId (shareCode: string): Promise < GeneralCallResult & {
async fromShareLinkFindSetId (shareCode: string): Promise<GeneralCallResult & {
fileSetId: string;
} > {
}> {
const flashService = this.context.session.getFlashTransferService();
const result = await flashService.getFileSetIdByCode(shareCode);
@@ -110,7 +130,7 @@ export class NTQQFlashApi {
* == 注意返回结构和其它的不同,没有GeneralCallResult!!! ==
* @param fileSetId
*/
async getFileListBySetId (fileSetId: string): Promise < FileListResponse > {
async getFileListBySetId (fileSetId: string): Promise<FileListResponse> {
const flashService = this.context.session.getFlashTransferService();
const requestArg = {
@@ -153,11 +173,11 @@ export class NTQQFlashApi {
* 获取闪传文件集合信息
* @param fileSetId
*/
async getFileSetIndoBySetId (fileSetId: string): Promise < GeneralCallResult & {
async getFileSetIndoBySetId (fileSetId: string): Promise<GeneralCallResult & {
seq: number;
isCache: boolean;
fileSet: FlashFileSetInfo;
} > {
}> {
const flashService = this.context.session.getFlashTransferService();
const requestArg = {
@@ -178,13 +198,13 @@ export class NTQQFlashApi {
* @param fileSetId
* @param peer
*/
async sendFlashMessage (fileSetId: string, peer:Peer): Promise < {
async sendFlashMessage (fileSetId: string, peer: Peer): Promise<{
errCode: number,
errMsg: string,
rsp: {
sendStatus: SendStatus[]
}
} > {
sendStatus: SendStatus[];
};
}> {
const flashService = this.context.session.getFlashTransferService();
const target = {
@@ -212,9 +232,9 @@ export class NTQQFlashApi {
* @param fileSetId
* @param options
*/
async getFileTransUrl (fileSetId: string, options: { fileName?: string; fileIndex?: number }): Promise < GeneralCallResult & {
async getFileTransUrl (fileSetId: string, options: { fileName?: string; fileIndex?: number; }): Promise<GeneralCallResult & {
transferUrl: string;
} > {
}> {
const flashService = this.context.session.getFlashTransferService();
const result = await this.getFileListBySetId(fileSetId);
@@ -261,4 +281,27 @@ export class NTQQFlashApi {
};
}
}
async createFileThumbnail (filePath: string): Promise<any> {
const msgService = this.context.session.getMsgService();
const savePath = msgService.getFileThumbSavePathForSend(750, true);
const result = await this.core.util.createThumbnailImage(
'flashtransfer',
filePath,
savePath,
{
width: 520,
height: 520,
},
'jpeg',
null
);
if (result.result === 0) {
this.context.logger.log('获取缩略图成功!!');
result.targetPath = savePath;
return result;
}
return result;
}
}
+1 -1
View File
@@ -43,7 +43,7 @@ export class NTQQFriendApi {
return retMap;
}
async delBuudy (uid: string, tempBlock = false, tempBothDel = false) {
async delBuddy (uid: string, tempBlock = false, tempBothDel = false) {
return this.context.session.getBuddyService().delBuddy({
friendUid: uid,
tempBlock,
+7 -6
View File
@@ -114,8 +114,9 @@ export class NTQQOnlineApi {
fileElement: {
fileName: actualFolderName,
filePath: folderPath,
fileSize: "",
},
} as any;
};
const msgService = this.context.session.getMsgService();
const startTime = Math.floor(Date.now() / 1000) - 2;
@@ -173,7 +174,7 @@ export class NTQQOnlineApi {
* 获取好友的在线文件消息
* @param peer
*/
async getOnlineFileMsg (peer: Peer) : Promise<any> {
async getOnlineFileMsg (peer: Peer): Promise<any> {
const msgService = this.context.session.getMsgService();
return await msgService.getOnlineFileMsgs(peer);
}
@@ -183,7 +184,7 @@ export class NTQQOnlineApi {
* @param peer
* @param msgId
*/
async cancelMyOnlineFileMsg (peer: Peer, msgId: string) : Promise<void> {
async cancelMyOnlineFileMsg (peer: Peer, msgId: string): Promise<void> {
const msgService = this.context.session.getMsgService();
await msgService.cancelSendMsg(peer, msgId);
}
@@ -194,7 +195,7 @@ export class NTQQOnlineApi {
* @param msgId
* @param elementId
*/
async refuseOnlineFileMsg (peer: Peer, msgId: string, elementId: string) : Promise<void> {
async refuseOnlineFileMsg (peer: Peer, msgId: string, elementId: string): Promise<void> {
const msgService = this.context.session.getMsgService();
const arrToSend = {
msgId,
@@ -215,7 +216,7 @@ export class NTQQOnlineApi {
* @param elementId
* @constructor
*/
async receiveOnlineFileOrFolder (peer: Peer, msgId: string, elementId: string) : Promise<any> {
async receiveOnlineFileOrFolder (peer: Peer, msgId: string, elementId: string): Promise<any> {
const msgService = this.context.session.getMsgService();
const arrToSend = {
msgId,
@@ -233,7 +234,7 @@ export class NTQQOnlineApi {
* @param peer
* @param msgId
*/
async switchFileToOffline (peer: Peer, msgId: string) : Promise<void> {
async switchFileToOffline (peer: Peer, msgId: string): Promise<void> {
const msgService = this.context.session.getMsgService();
await msgService.switchToOfflineSendMsg(peer, msgId);
}
+134 -100
View File
@@ -1,5 +1,5 @@
export interface FlashBaseRequest {
fileSetId: string
fileSetId: string;
}
export interface UploaderInfo {
@@ -19,14 +19,14 @@ export interface thumbnailInfo {
}
export interface SendTarget {
destType: number // 1私聊
destType: number; // 1私聊
destUin?: string,
destUid: string,
}
export interface SendTargetRequests {
fileSetId: string
targets: SendTarget[]
fileSetId: string;
targets: SendTarget[];
}
export interface DownloadStatusInfo {
@@ -53,13 +53,13 @@ export interface DownloadStatusInfo {
isAllFileAlreadyDownloaded: boolean,
saveFileSetDir: string,
allWaitingStatusTask: boolean,
downloadSceneType: number,
downloadSceneType: DownloadSceneType,
retryCount: number,
statisticInfo: {
downloadTaskId: string,
downloadFilesetName: string,
downloadFileTypeDistribution: string,
downloadFileSizeDistribution: string
downloadFileSizeDistribution: string;
},
albumStorageFailImageNum: number,
albumStorageFailVideoNum: number,
@@ -67,8 +67,8 @@ export interface DownloadStatusInfo {
albumStorageSucImageNum: number,
albumStorageSucVideoNum: number,
albumStorageSucFileIdList: [],
albumStorageFileNum: number
}
albumStorageFileNum: number;
};
}
export interface physicalInfo {
@@ -95,94 +95,94 @@ export interface uploadInfo {
svrRrrCode: number,
errMsg: string,
isNeedDelDeviceInfo: boolean,
thumbnailUploadState: number
thumbnailUploadState: number;
isSecondHit: boolean,
hasModifiedErr: boolean,
}
export interface folderUploadInfo {
totalUploadedFileSize: string
successCount: number
failedCount: number
totalUploadedFileSize: string;
successCount: number;
failedCount: number;
}
export interface folderDownloadInfo {
totalDownloadedFileSize: string
totalFileSize: string
totalDownloadFileCount: number
successCount: number
failedCount: number
pausedCount: number
cancelCount: number
downloadingCount: number
partialDownloadCount: number
curLevelDownloadedFileCount: number
curLevelUnDownloadedFileCount: number
totalDownloadedFileSize: string;
totalFileSize: string;
totalDownloadFileCount: number;
successCount: number;
failedCount: number;
pausedCount: number;
cancelCount: number;
downloadingCount: number;
partialDownloadCount: number;
curLevelDownloadedFileCount: number;
curLevelUnDownloadedFileCount: number;
}
export interface compressFileFolderInfo {
downloadStatus: number
saveFileDirPath: string
totalFileCount: string
totalFileSize: string
downloadStatus: number;
saveFileDirPath: string;
totalFileCount: string;
totalFileSize: string;
}
export interface albumStorgeInfo {
status: number
localIdentifier: string
errorCode: number
timeCost: number
status: number;
localIdentifier: string;
errorCode: number;
timeCost: number;
}
export interface FlashOneFileInfo {
fileSetId: string
cliFileId: string // client?? 或许可以换取url
compressedFileFolderId: string
archiveIndex: 0
indexPath: string
isDir: boolean // 文件或者文件夹!!
parentId: string
depth: number // 1
cliFileIndex: number
fileType: number // 枚举!! 已完成枚举!!
name: string
namePinyin: string
isCover: boolean
isCoverOriginal: boolean
fileSize: string
fileCount: number
thumbnail: thumbnailInfo
physical: physicalInfo
srvFileId: string // service?? 服务器上面的id吗?
srvParentFileId: string
svrLastUpdateTimestamp: string
downloadInfo: downloadInfo
saveFilePath: string
search_relative_path: string
disk_relative_path: string
uploadInfo: uploadInfo
status: number
uploadStatus: number // 3已上传成功
downloadStatus: number // 0未下载
folderUploadInfo: folderUploadInfo
folderDownloadInfo: folderDownloadInfo
sha1: string
bookmark: string
compressFileFolderInfo: compressFileFolderInfo
uploadPauseReason: string
downloadPauseReason: string
filePhysicalSize: string
thumbnail_sha1: string | null
thumbnail_size: string | null
needAlbumStorage: boolean
albumStorageInfo: albumStorgeInfo
fileSetId: string;
cliFileId: string; // client?? 或许可以换取url
compressedFileFolderId: string;
archiveIndex: 0;
indexPath: string;
isDir: boolean; // 文件或者文件夹!!
parentId: string;
depth: number; // 1
cliFileIndex: number;
fileType: number; // 枚举!! 已完成枚举!!
name: string;
namePinyin: string;
isCover: boolean;
isCoverOriginal: boolean;
fileSize: string;
fileCount: number;
thumbnail: thumbnailInfo;
physical: physicalInfo;
srvFileId: string; // service?? 服务器上面的id吗?
srvParentFileId: string;
svrLastUpdateTimestamp: string;
downloadInfo: downloadInfo;
saveFilePath: string;
search_relative_path: string;
disk_relative_path: string;
uploadInfo: uploadInfo;
status: number;
uploadStatus: number; // 3已上传成功
downloadStatus: number; // 0未下载
folderUploadInfo: folderUploadInfo;
folderDownloadInfo: folderDownloadInfo;
sha1: string;
bookmark: string;
compressFileFolderInfo: compressFileFolderInfo;
uploadPauseReason: string;
downloadPauseReason: string;
filePhysicalSize: string;
thumbnail_sha1: string | null;
thumbnail_size: string | null;
needAlbumStorage: boolean;
albumStorageInfo: albumStorgeInfo;
}
export interface fileListsInfo {
parentId: string,
depth: number, // 1
fileList: FlashOneFileInfo[],
paginationInfo: {}
paginationInfo: {};
isEnd: boolean,
isCache: boolean,
}
@@ -200,30 +200,50 @@ export interface createFlashTransferResult {
expireTime: string,
expireLeftTime: string,
}
export enum UploadSceneType {
KUPLOADSCENEUNKNOWN,
KUPLOADSCENEFLOATWINDOWRIGHTCLICKMENU,
KUPLOADSCENEFLOATWINDOWDRAG,
KUPLOADSCENEFLOATWINDOWFILESELECTOR,
KUPLOADSCENEFLOATWINDOWSHORTCUTKEYCTRLCV,
KUPLOADSCENEH5LAUNCHCLIENTRIGHTCLICKMENU,
KUPLOADSCENEH5LAUNCHCLIENTDRAG,
KUPLOADSCENEH5LAUNCHCLIENTFILESELECTOR,
KUPLOADSCENEH5LAUNCHCLIENTSHORTCUTKEYCTRLCV,
KUPLOADSCENEAIODRAG,
KUPLOADSCENEAIOFILESELECTOR,
KUPLOADSCENEAIOSHORTCUTKEYCTRLCV
}
export interface StartFlashTaskRequests {
screen?: number; // 1 PC-QQ
screen: number; // 1 PC-QQ
name?: string;
uploaders: UploaderInfo[];
permission?: {};
coverPath?: string;
paths: string[]; // 文件的绝对路径,可以是文件夹
// excludePaths: [];
// expireLeftTime: 0,
// isNeedDelDeviceInfo: boolean,
// isNeedDelLocation: boolean,
// coverOriginalInfos: [],
// uploadSceneType: 10, // 不知道怎么枚举 先硬编码吧
// detectPrivacyInfoResult: {
// exists: boolean,
// allDetectResults: {}
// }
excludePaths?: string[];
expireLeftTime?: number, // 0
isNeedDelDeviceInfo: boolean,
isNeedDelLocation: boolean,
coverOriginalInfos?: {
path: string,
thumbnailPath: string,
}[],
uploadSceneType: UploadSceneType, // 不知道怎么枚举 先硬编码吧 (PC QQ 10)
detectPrivacyInfoResult: {
exists: boolean,
allDetectResults: {};
};
}
export enum BusiScene {
KBUSISCENEINVALID,
KBUSISCENEFLASHSCENE
}
export interface FileListInfoRequests {
seq: number, // 0
fileSetId: string,
isUseCache: boolean,
sceneType: number, // 1
sceneType: BusiScene, // 1
reqInfos: {
count: number, // 18 ?? 硬编码吧 不懂
paginationInfo: {},
@@ -238,10 +258,24 @@ export interface FileListInfoRequests {
sortField: number,
sortOrder: number,
}[],
isNeedPhysicalInfoReady: boolean
}[]
isNeedPhysicalInfoReady: boolean;
}[];
}
export enum DownloadSceneType {
KDOWNLOADSCENEUNKNOWN,
KDOWNLOADSCENEARKC2C,
KDOWNLOADSCENEARKC2CDETAILPAGE,
KDOWNLOADSCENEARKGROUP,
KDOWNLOADSCENEARKGROUPDETAILPAGE,
KDOWNLOADSCENELINKC2C,
KDOWNLOADSCENELINKGROUP,
KDOWNLOADSCENELINKCHANNEL,
KDOWNLOADSCENELINKTEMPCHAT,
KDOWNLOADSCENELINKOTHERINQQ,
KDOWNLOADSCENESCANQRCODE,
KDWONLOADSCENEFLASHTRANSFERCENTERCLIENT,
KDWONLOADSCENEFLASHTRANSFERCENTERSCHEMA
}
export interface FlashFileSetInfo {
fileSetId: string,
name: string,
@@ -258,23 +292,23 @@ export interface FlashFileSetInfo {
urls: [
{
spec: number, // 2
url: string
url: string;
}
],
localCachePath: string
localCachePath: string;
},
uploaders: [
{
uin: string,
nickname: string,
uid: string,
sendEntrance: string
sendEntrance: string;
}
],
expireLeftTime: number,
aiClusteringStatus: {
firstClusteringList: [],
shouldPull: boolean
shouldPull: boolean;
},
createTime: number,
expireTime: number,
@@ -284,7 +318,7 @@ export interface FlashFileSetInfo {
uploadInfo: {
totalUploadedFileSize: number,
successCount: number,
failedCount: number
failedCount: number;
},
downloadInfo: {
totalDownloadedFileSize: 0,
@@ -296,7 +330,7 @@ export interface FlashFileSetInfo {
cancelCount: 0,
status: 0,
curLevelDownloadedFileCount: number,
curLevelUnDownloadedFileCount: 0
curLevelUnDownloadedFileCount: 0;
},
transferType: number,
isLocalCreate: true,
@@ -306,12 +340,12 @@ export interface FlashFileSetInfo {
downloadStatus: 0,
downloadPauseReason: 0,
saveFileSetDir: string,
uploadSceneType: 10,
downloadSceneType: 0, // 0 PC-QQ 103 web
uploadSceneType: UploadSceneType,
downloadSceneType: DownloadSceneType, // 0 PC-QQ 103 web
retryCount: number,
isMergeShareUpload: 0,
isRemoveDeviceInfo: boolean,
isRemoveLocation: boolean
isRemoveLocation: boolean;
}
export interface SendStatus {
@@ -320,5 +354,5 @@ export interface SendStatus {
target: {
destType: number,
destUid: string,
}
};
}
+7
View File
@@ -39,6 +39,12 @@ export * from './wrapper';
export * from './types/index';
export * from './services/index';
export * from './listeners/index';
export * from './apis/index';
export * from './helper/log';
export * from './helper/qq-basic-info';
export * from './helper/event';
export * from './helper/config';
export * from './helper/proxy-handler';
export enum NapCatCoreWorkingEnv {
Unknown = 0,
@@ -74,6 +80,7 @@ export function loadQQWrapper (execPath: string | undefined, QQVersion: string):
}
const nativemodule: { exports: WrapperNodeApi; } = { exports: {} as WrapperNodeApi };
process.dlopen(nativemodule, wrapperNodePath);
process.env['NAPCAT_WRAPPER_PATH'] = wrapperNodePath;
return nativemodule.exports;
}
export function getMajorPath (execPath: string, QQVersion: string): string {
@@ -10,6 +10,7 @@ import {
DownloadStatusInfo,
SendTargetRequests,
FlashOneFileInfo,
DownloadSceneType,
} from '../data/flash';
export interface NodeIKernelFlashTransferService {
@@ -18,48 +19,48 @@ export interface NodeIKernelFlashTransferService {
* @param timestamp
* @param fileInfo
*/
createFlashTransferUploadTask(timestamp: number, fileInfo: StartFlashTaskRequests): Promise < GeneralCallResult & {
createFlashTransferUploadTask (timestamp: number, fileInfo: StartFlashTaskRequests): Promise<GeneralCallResult & {
createFlashTransferResult: createFlashTransferResult;
seq: number;
} >; // 2 arg 重点 // 自动上传
}>; // 2 arg 重点 // 自动上传
createMergeShareTask(...args: unknown[]): unknown; // 2 arg
createMergeShareTask (...args: unknown[]): unknown; // 2 arg
updateFlashTransfer(...args: unknown[]): unknown; // 2 arg
updateFlashTransfer (...args: unknown[]): unknown; // 2 arg
getFileSetList(...args: unknown[]): unknown; // 1 arg
getFileSetList (...args: unknown[]): unknown; // 1 arg
getFileSetListCount(...args: unknown[]): unknown; // 1 arg
getFileSetListCount (...args: unknown[]): unknown; // 1 arg
/**
* 获取file set 的信息
* @param fileSetIdDict
*/
getFileSet(fileSetIdDict: FlashBaseRequest): Promise < GeneralCallResult & {
getFileSet (fileSetIdDict: FlashBaseRequest): Promise<GeneralCallResult & {
seq: number;
isCache: boolean;
fileSet: FlashFileSetInfo;
} >; // 1 arg
}>; // 1 arg
/**
* 获取file set 里面的文件信息(文件夹结构)
* @param requestArgs
*/
getFileList(requestArgs: FileListInfoRequests): Promise < {
getFileList (requestArgs: FileListInfoRequests): Promise<{
rsp: FileListResponse;
} > ; // 1 arg 这个方法QQ有bug??? 并没有,是我参数有问题
}>; // 1 arg 这个方法QQ有bug??? 并没有,是我参数有问题
getDownloadedFileCount(...args: unknown[]): unknown; // 1 arg
getDownloadedFileCount (...args: unknown[]): unknown; // 1 arg
getLocalFileList(...args: unknown[]): unknown; // 3 arg
getLocalFileList (...args: unknown[]): unknown; // 3 arg
batchRemoveUserFileSetHistory(...args: unknown[]): unknown; // 1 arg
batchRemoveUserFileSetHistory (...args: unknown[]): unknown; // 1 arg
/**
* 获取分享链接
* @param fileSetId
*/
getShareLinkReq(fileSetId:string): Promise< GeneralCallResult & {
getShareLinkReq (fileSetId: string): Promise<GeneralCallResult & {
shareLink: string;
expireTimestamp: string;
}>;
@@ -68,235 +69,235 @@ export interface NodeIKernelFlashTransferService {
* 由分享链接到fileSetId
* @param shareCode
*/
getFileSetIdByCode(shareCode: string): Promise < GeneralCallResult & {
getFileSetIdByCode (shareCode: string): Promise<GeneralCallResult & {
fileSetId: string;
} > ; // 1 arg code == share code
}>; // 1 arg code == share code
batchRemoveFile(...args: unknown[]): unknown; // 1 arg
batchRemoveFile (...args: unknown[]): unknown; // 1 arg
checkUploadPathValid(...args: unknown[]): unknown; // 1 arg
checkUploadPathValid (...args: unknown[]): unknown; // 1 arg
cleanFailedFiles(...args: unknown[]): unknown; // 2 arg
cleanFailedFiles (...args: unknown[]): unknown; // 2 arg
/**
* 暂停所有的任务
*/
resumeAllUnfinishedTasks(): unknown; // 0 arg !!
resumeAllUnfinishedTasks (): unknown; // 0 arg !!
addFileSetUploadListener(...args: unknown[]): unknown; // 1 arg
addFileSetUploadListener (...args: unknown[]): unknown; // 1 arg
removeFileSetUploadListener(...args: unknown[]): unknown; // 1 arg
removeFileSetUploadListener (...args: unknown[]): unknown; // 1 arg
/**
* 开始上传任务 适用于已暂停的
* @param fileSetId
*/
startFileSetUpload(fileSetId: string): void; // 1 arg 并不是新建任务,应该是暂停后的启动
startFileSetUpload (fileSetId: string): void; // 1 arg 并不是新建任务,应该是暂停后的启动
/**
* 结束,无法再次启动
* @param fileSetId
*/
stopFileSetUpload(fileSetId: string): void; // 1 arg stop 后start无效
stopFileSetUpload (fileSetId: string): void; // 1 arg stop 后start无效
/**
* 暂停上传
* @param fileSetId
*/
pauseFileSetUpload(fileSetId: string): void; // 1 arg 暂停上传
pauseFileSetUpload (fileSetId: string): void; // 1 arg 暂停上传
/**
* 继续上传
* @param args
*/
resumeFileSetUpload(...args: unknown[]): unknown; // 1 arg 继续
resumeFileSetUpload (...args: unknown[]): unknown; // 1 arg 继续
pauseFileUpload(...args: unknown[]): unknown; // 1 arg
pauseFileUpload (...args: unknown[]): unknown; // 1 arg
resumeFileUpload(...args: unknown[]): unknown; // 1 arg
resumeFileUpload (...args: unknown[]): unknown; // 1 arg
stopFileUpload(...args: unknown[]): unknown; // 1 arg
stopFileUpload (...args: unknown[]): unknown; // 1 arg
asyncGetThumbnailPath(...args: unknown[]): unknown; // 2 arg
asyncGetThumbnailPath (...args: unknown[]): unknown; // 2 arg
setDownLoadDefaultFileDir(...args: unknown[]): unknown; // 1 arg
setDownLoadDefaultFileDir (...args: unknown[]): unknown; // 1 arg
setFileSetDownloadDir(...args: unknown[]): unknown; // 2 arg
setFileSetDownloadDir (...args: unknown[]): unknown; // 2 arg
getFileSetDownloadDir(...args: unknown[]): unknown; // 1 arg
getFileSetDownloadDir (...args: unknown[]): unknown; // 1 arg
setFlashTransferDir(...args: unknown[]): unknown; // 2 arg
setFlashTransferDir (...args: unknown[]): unknown; // 2 arg
addFileSetDownloadListener(...args: unknown[]): unknown; // 1 arg
addFileSetDownloadListener (...args: unknown[]): unknown; // 1 arg
removeFileSetDownloadListener(...args: unknown[]): unknown; // 1 arg
removeFileSetDownloadListener (...args: unknown[]): unknown; // 1 arg
/**
* 开始下载file set的函数 同开始上传
* @param fileSetId
* @param chatType 聊天类型 //因为没有peer,其实可以硬编码为1 (好友私聊)
* @param downloadSceneType 下载类型 //因为没有peer,其实可以硬编码为1 (好友私聊)
* @param arg // 默认为false
*/
startFileSetDownload(fileSetId:string, chatType: number, arg: { isIncludeCompressInnerFiles: boolean }): Promise < GeneralCallResult & {
extraInfo: 0
} >; // 3 arg
startFileSetDownload (fileSetId: string, downloadSceneType: DownloadSceneType, downloadOptionParams: { isIncludeCompressInnerFiles: boolean; }): Promise<GeneralCallResult & {
extraInfo: 0;
}>; // 3 arg
stopFileSetDownload(fileSetId: string, arg1: { isIncludeCompressInnerFiles: boolean }): Promise < GeneralCallResult & {
extraInfo: 0
} > ; // 2 arg 结束不可重启!!
stopFileSetDownload (fileSetId: string, downloadOptionParams: { isIncludeCompressInnerFiles: boolean; }): Promise<GeneralCallResult & {
extraInfo: 0;
}>; // 2 arg 结束不可重启!!
pauseFileSetDownload(fileSetId: string, arg1: { isIncludeCompressInnerFiles: boolean }): Promise < GeneralCallResult & {
extraInfo: 0
} > ; // 2 arg
pauseFileSetDownload (fileSetId: string, downloadOptionParams: { isIncludeCompressInnerFiles: boolean; }): Promise<GeneralCallResult & {
extraInfo: 0;
}>; // 2 arg
resumeFileSetDownload(fileSetId: string, arg1: { isIncludeCompressInnerFiles: boolean }): Promise < GeneralCallResult & {
extraInfo: 0
} > ; // 2 arg
resumeFileSetDownload (fileSetId: string, downloadOptionParams: { isIncludeCompressInnerFiles: boolean; }): Promise<GeneralCallResult & {
extraInfo: 0;
}>; // 2 arg
startFileListDownLoad(...args: unknown[]): unknown; // 4 arg // 大概率是选择set里面的部分文件进行下载,没必要,不想写
startFileListDownLoad (...args: unknown[]): unknown; // 4 arg // 大概率是选择set里面的部分文件进行下载,没必要,不想写
pauseFileListDownLoad(...args: unknown[]): unknown; // 2 arg
pauseFileListDownLoad (...args: unknown[]): unknown; // 2 arg
resumeFileListDownLoad(...args: unknown[]): unknown; // 2 arg
resumeFileListDownLoad (...args: unknown[]): unknown; // 2 arg
stopFileListDownLoad(...args: unknown[]): unknown; // 2 arg
stopFileListDownLoad (...args: unknown[]): unknown; // 2 arg
startThumbnailListDownload(fileSetId: string): Promise < GeneralCallResult >; // 1 arg // 缩略图下载
startThumbnailListDownload (fileSetId: string): Promise<GeneralCallResult>; // 1 arg // 缩略图下载
stopThumbnailListDownload(fileSetId: string): Promise < GeneralCallResult >; // 1 arg
stopThumbnailListDownload (fileSetId: string): Promise<GeneralCallResult>; // 1 arg
asyncRequestDownLoadStatus(fileSetId: string): Promise < DownloadStatusInfo >; // 1 arg
asyncRequestDownLoadStatus (fileSetId: string): Promise<DownloadStatusInfo>; // 1 arg
startFileTransferUrl(fileInfo: FlashOneFileInfo): Promise < {
startFileTransferUrl (fileInfo: FlashOneFileInfo): Promise<{
ret: number,
url: string,
expireTimestampSeconds: string
} >; // 1 arg
expireTimestampSeconds: string;
}>; // 1 arg
startFileListDownLoadBySessionId(...args: unknown[]): unknown; // 2 arg
startFileListDownLoadBySessionId (...args: unknown[]): unknown; // 2 arg
addFileSetSimpleStatusListener(...args: unknown[]): unknown; // 2 arg
addFileSetSimpleStatusListener (...args: unknown[]): unknown; // 2 arg
addFileSetSimpleStatusMonitoring(...args: unknown[]): unknown; // 2 arg
addFileSetSimpleStatusMonitoring (...args: unknown[]): unknown; // 2 arg
removeFileSetSimpleStatusMonitoring(...args: unknown[]): unknown; // 2 arg
removeFileSetSimpleStatusMonitoring (...args: unknown[]): unknown; // 2 arg
removeFileSetSimpleStatusListener(...args: unknown[]): unknown; // 1 arg
removeFileSetSimpleStatusListener (...args: unknown[]): unknown; // 1 arg
addDesktopFileSetSimpleStatusListener(...args: unknown[]): unknown; // 1 arg
addDesktopFileSetSimpleStatusListener (...args: unknown[]): unknown; // 1 arg
addDesktopFileSetSimpleStatusMonitoring(...args: unknown[]): unknown; // 1 arg
addDesktopFileSetSimpleStatusMonitoring (...args: unknown[]): unknown; // 1 arg
removeDesktopFileSetSimpleStatusMonitoring(...args: unknown[]): unknown; // 1 arg
removeDesktopFileSetSimpleStatusMonitoring (...args: unknown[]): unknown; // 1 arg
removeDesktopFileSetSimpleStatusListener(...args: unknown[]): unknown; // 1 arg
removeDesktopFileSetSimpleStatusListener (...args: unknown[]): unknown; // 1 arg
addFileSetSimpleUploadInfoListener(...args: unknown[]): unknown; // 1 arg
addFileSetSimpleUploadInfoListener (...args: unknown[]): unknown; // 1 arg
addFileSetSimpleUploadInfoMonitoring(...args: unknown[]): unknown; // 1 arg
addFileSetSimpleUploadInfoMonitoring (...args: unknown[]): unknown; // 1 arg
removeFileSetSimpleUploadInfoMonitoring(...args: unknown[]): unknown; // 1 arg
removeFileSetSimpleUploadInfoMonitoring (...args: unknown[]): unknown; // 1 arg
removeFileSetSimpleUploadInfoListener(...args: unknown[]): unknown; // 1 arg
removeFileSetSimpleUploadInfoListener (...args: unknown[]): unknown; // 1 arg
/**
* 发送闪传消息
* @param sendArgs
*/
sendFlashTransferMsg(sendArgs: SendTargetRequests): Promise < {
sendFlashTransferMsg (sendArgs: SendTargetRequests): Promise<{
errCode: number,
errMsg: string,
rsp: {
sendStatus: SendStatus[]
}
} >; // 1 arg 估计是file set id
sendStatus: SendStatus[];
};
}>; // 1 arg 估计是file set id
addFlashTransferTaskInfoListener(...args: unknown[]): unknown; // 1 arg
addFlashTransferTaskInfoListener (...args: unknown[]): unknown; // 1 arg
removeFlashTransferTaskInfoListener(...args: unknown[]): unknown; // 1 arg
removeFlashTransferTaskInfoListener (...args: unknown[]): unknown; // 1 arg
retrieveLocalLastFailedSetTasksInfo(): unknown; // 0 arg
retrieveLocalLastFailedSetTasksInfo (): unknown; // 0 arg
getFailedFileList(fileSetId: string): Promise < {
getFailedFileList (fileSetId: string): Promise<{
rsp: {
seq: number;
result: number;
errMs: string;
fileSetId: string;
fileList: []
}
} >; // 1 arg
fileList: [];
};
}>; // 1 arg
getLocalFileListByStatuses(...args: unknown[]): unknown; // 1 arg
getLocalFileListByStatuses (...args: unknown[]): unknown; // 1 arg
addTransferStateListener(...args: unknown[]): unknown; // 1 arg
addTransferStateListener (...args: unknown[]): unknown; // 1 arg
removeTransferStateListener(...args: unknown[]): unknown; // 1 arg
removeTransferStateListener (...args: unknown[]): unknown; // 1 arg
getFileSetFirstClusteringList(...args: unknown[]): unknown; // 3 arg
getFileSetFirstClusteringList (...args: unknown[]): unknown; // 3 arg
getFileSetClusteringList(...args: unknown[]): unknown; // 1 arg
getFileSetClusteringList (...args: unknown[]): unknown; // 1 arg
addFileSetClusteringListListener(...args: unknown[]): unknown; // 1 arg
addFileSetClusteringListListener (...args: unknown[]): unknown; // 1 arg
removeFileSetClusteringListListener(...args: unknown[]): unknown; // 1 arg
removeFileSetClusteringListListener (...args: unknown[]): unknown; // 1 arg
getFileSetClusteringDetail(...args: unknown[]): unknown; // 1 arg
getFileSetClusteringDetail (...args: unknown[]): unknown; // 1 arg
doAIOFlashTransferBubbleActionWithStatus(...args: unknown[]): unknown; // 4 arg
doAIOFlashTransferBubbleActionWithStatus (...args: unknown[]): unknown; // 4 arg
getFilesTransferProgress(...args: unknown[]): unknown; // 1 arg
getFilesTransferProgress (...args: unknown[]): unknown; // 1 arg
pollFilesTransferProgress(...args: unknown[]): unknown; // 1 arg
pollFilesTransferProgress (...args: unknown[]): unknown; // 1 arg
cancelPollFilesTransferProgress(...args: unknown[]): unknown; // 1 arg
cancelPollFilesTransferProgress (...args: unknown[]): unknown; // 1 arg
checkDownloadStatusBeforeLocalFileOper(...args: unknown[]): unknown; // 3 arg
checkDownloadStatusBeforeLocalFileOper (...args: unknown[]): unknown; // 3 arg
getCompressedFileFolder(...args: unknown[]): unknown; // 1 arg
getCompressedFileFolder (...args: unknown[]): unknown; // 1 arg
addFolderListener(...args: unknown[]): unknown; // 1 arg
addFolderListener (...args: unknown[]): unknown; // 1 arg
removeFolderListener(...args: unknown[]): unknown;
removeFolderListener (...args: unknown[]): unknown;
addCompressedFileListener(...args: unknown[]): unknown;
addCompressedFileListener (...args: unknown[]): unknown;
removeCompressedFileListener(...args: unknown[]): unknown;
removeCompressedFileListener (...args: unknown[]): unknown;
getFileCategoryList(...args: unknown[]): unknown;
getFileCategoryList (...args: unknown[]): unknown;
addDeviceStatusListener(...args: unknown[]): unknown;
addDeviceStatusListener (...args: unknown[]): unknown;
removeDeviceStatusListener(...args: unknown[]): unknown;
removeDeviceStatusListener (...args: unknown[]): unknown;
checkDeviceStatus(...args: unknown[]): unknown;
checkDeviceStatus (...args: unknown[]): unknown;
pauseAllTasks(...args: unknown[]): unknown; // 2 arg
pauseAllTasks (...args: unknown[]): unknown; // 2 arg
resumePausedTasksAfterDeviceStatus(...args: unknown[]): unknown;
resumePausedTasksAfterDeviceStatus (...args: unknown[]): unknown;
onSystemGoingToSleep(...args: unknown[]): unknown;
onSystemGoingToSleep (...args: unknown[]): unknown;
onSystemWokeUp(...args: unknown[]): unknown;
onSystemWokeUp (...args: unknown[]): unknown;
getFileMetas(...args: unknown[]): unknown;
getFileMetas (...args: unknown[]): unknown;
addDownloadCntStatisticsListener(...args: unknown[]): unknown;
addDownloadCntStatisticsListener (...args: unknown[]): unknown;
removeDownloadCntStatisticsListener(...args: unknown[]): unknown;
removeDownloadCntStatisticsListener (...args: unknown[]): unknown;
detectPrivacyInfoInPaths(...args: unknown[]): unknown;
detectPrivacyInfoInPaths (...args: unknown[]): unknown;
getFileThumbnailUrl(...args: unknown[]): unknown;
getFileThumbnailUrl (...args: unknown[]): unknown;
handleDownloadFinishAfterSaveToAlbum(...args: unknown[]): unknown;
handleDownloadFinishAfterSaveToAlbum (...args: unknown[]): unknown;
checkBatchFilesDownloadStatus(...args: unknown[]): unknown;
checkBatchFilesDownloadStatus (...args: unknown[]): unknown;
onCheckAlbumStorageStatusResult(...args: unknown[]): unknown;
onCheckAlbumStorageStatusResult (...args: unknown[]): unknown;
addFileAlbumStorageListener(...args: unknown[]): unknown;
addFileAlbumStorageListener (...args: unknown[]): unknown;
removeFileAlbumStorageListener(...args: unknown[]): unknown;
removeFileAlbumStorageListener (...args: unknown[]): unknown;
refreshFolderStatus(...args: unknown[]): unknown;
refreshFolderStatus (...args: unknown[]): unknown;
}
@@ -336,7 +336,7 @@ export interface NodeIKernelMsgService {
assembleMobileQQRichMediaFilePath (...args: unknown[]): unknown;
getFileThumbSavePathForSend (...args: unknown[]): unknown;
getFileThumbSavePathForSend (thumbSize: number, createNeed: boolean): string;
getFileThumbSavePath (...args: unknown[]): unknown;
+4
View File
@@ -11,3 +11,7 @@ export * from './constant';
export * from './graytip';
export * from './emoji';
export * from './service';
export * from './adapter';
export * from './contact';
export * from './file';
export * from './flashfile';
+1 -1
View File
@@ -1,4 +1,4 @@
import { NTGroupMemberRole } from '@/napcat-core/index';
import { NTGroupMemberRole } from './group';
import { ActionBarElement, ArkElement, AvRecordElement, CalendarElement, FaceBubbleElement, FaceElement, FileElement, GiphyElement, GrayTipElement, MarketFaceElement, PicElement, PttElement, RecommendedMsgElement, ReplyElement, ShareLocationElement, StructLongMsgElement, TaskTopMsgElement, TextElement, TofuRecordElement, VideoElement, YoloGameResultElement } from './element';
/*
+121 -108
View File
@@ -1,5 +1,6 @@
import { NodeIDependsAdapter, NodeIDispatcherAdapter, NodeIGlobalAdapter } from './adapters';
import {
GeneralCallResult,
NodeIKernelAvatarService,
NodeIKernelBuddyService,
NodeIKernelGroupService,
@@ -27,78 +28,78 @@ import { NodeIKernelMSFService } from './services/NodeIKernelMSFService';
import { NodeIkernelTestPerformanceService } from './services/NodeIkernelTestPerformanceService';
import { NodeIKernelECDHService } from './services/NodeIKernelECDHService';
import { NodeIO3MiscService } from './services/NodeIO3MiscService';
import { NodeIKernelFlashTransferService } from "./services/NodeIKernelFlashTransferService";
import { NodeIKernelFlashTransferService } from './services/NodeIKernelFlashTransferService';
export interface NodeQQNTWrapperUtil {
get(): NodeQQNTWrapperUtil;
get (): NodeQQNTWrapperUtil;
getNTUserDataInfoConfig(): string;
getNTUserDataInfoConfig (): string;
emptyWorkingSet(n: number): void;
emptyWorkingSet (n: number): void;
getSsoCmdOfOidbReq(arg1: number, arg2: number): unknown;
getSsoCmdOfOidbReq (arg1: number, arg2: number): unknown;
getSsoBufferOfOidbReq(...args: unknown[]): unknown; // 有点看不懂参数定义 待补充 好像是三个参数
getSsoBufferOfOidbReq (...args: unknown[]): unknown; // 有点看不懂参数定义 待补充 好像是三个参数
getOidbRspInfo(arg: string): unknown; // 可能是错的
getOidbRspInfo (arg: string): unknown; // 可能是错的
getFileSize(path: string): Promise<number>; // 直接的猜测
getFileSize (path: string): Promise<number>; // 直接的猜测
genFileMd5Buf(arg: string): unknown; // 可能是错的
genFileMd5Buf (arg: string): unknown; // 可能是错的
genFileMd5Hex(path: string): unknown; // 直接的猜测
genFileMd5Hex (path: string): unknown; // 直接的猜测
genFileShaBuf(path: string): unknown; // 直接的猜测
genFileShaBuf (path: string): unknown; // 直接的猜测
genFileCumulateSha1(path: string): unknown; // 直接的猜测
genFileCumulateSha1 (path: string): unknown; // 直接的猜测
genFileShaHex(path: string): unknown; // 直接的猜测
genFileShaHex (path: string): unknown; // 直接的猜测
fileIsExist(path: string): unknown;
fileIsExist (path: string): unknown;
startTrace(path: string): unknown; // 可能是错的
startTrace (path: string): unknown; // 可能是错的
copyFile(src: string, dst: string): unknown;
copyFile (src: string, dst: string): unknown;
genFileShaAndMd5Hex(path: string, unknown: number): unknown; // 可能是错的
genFileShaAndMd5Hex (path: string, unknown: number): unknown; // 可能是错的
setTraceInfo(unknown: unknown): unknown;
setTraceInfo (unknown: unknown): unknown;
encodeOffLine(unknown: unknown): unknown;
encodeOffLine (unknown: unknown): unknown;
decodeOffLine(arg: string): unknown; // 可能是错的 传递hex
decodeOffLine (arg: string): unknown; // 可能是错的 传递hex
DecoderRecentInfo(arg: string): unknown; // 可能是错的 传递hex
DecoderRecentInfo (arg: string): unknown; // 可能是错的 传递hex
getPinyin(arg0: string, arg1: boolean): unknown;
getPinyin (arg0: string, arg1: boolean): unknown;
matchInPinyin(arg0: unknown[], arg1: string): unknown; // 参数特复杂 arg0是个复杂数据类型
matchInPinyin (arg0: unknown[], arg1: string): unknown; // 参数特复杂 arg0是个复杂数据类型
makeDirByPath(arg0: string): unknown;
makeDirByPath (arg0: string): unknown;
emptyWorkingSet(arg0: number): unknown; // 参数是UINT32
emptyWorkingSet (arg0: number): unknown; // 参数是UINT32
runProcess(arg0: string, arg1: boolean): unknown;
runProcess (arg0: string, arg1: boolean): unknown;
runProcessArgs(arg0: string, arg1: { [key: string]: string }, arg2: boolean): unknown;
runProcessArgs (arg0: string, arg1: { [key: string]: string; }, arg2: boolean): unknown;
calcThumbSize(arg0: number, arg1: number, arg2: unknown): unknown;
calcThumbSize (arg0: number, arg1: number, arg2: unknown): unknown;
fullWordToHalfWord(word: string): unknown;
fullWordToHalfWord (word: string): unknown;
getNTUserDataInfoConfig(): unknown;
getNTUserDataInfoConfig (): unknown;
pathIsReadableAndWriteable(path: string): unknown; // 直接的猜测
pathIsReadableAndWriteable (path: string): unknown; // 直接的猜测
resetUserDataSavePathToDocument(): unknown;
resetUserDataSavePathToDocument (): unknown;
getSoBuildInfo(): unknown; // 例如 0[0]_d491dc01e0a_0
getSoBuildInfo (): unknown; // 例如 0[0]_d491dc01e0a_0
registerCountInstruments(arg0: string, arg1: string[], arg2: number, arg3: number): unknown;
registerCountInstruments (arg0: string, arg1: string[], arg2: number, arg3: number): unknown;
registerValueInstruments(arg0: string, arg1: string[], arg2: number, arg3: number): unknown;
registerValueInstruments (arg0: string, arg1: string[], arg2: number, arg3: number): unknown;
registerValueInstrumentsWithBoundary(
registerValueInstrumentsWithBoundary (
arg0: string,
arg1: unknown,
arg2: unknown,
@@ -106,7 +107,7 @@ export interface NodeQQNTWrapperUtil {
arg4: number,
): unknown;
reportCountIndicators(
reportCountIndicators (
arg0: string,
arg1: Map<unknown, unknown>,
arg2: string,
@@ -114,7 +115,7 @@ export interface NodeQQNTWrapperUtil {
arg4: boolean,
): unknown;
reportValueIndicators(
reportValueIndicators (
arg0: string,
arg1: Map<unknown, unknown>,
arg2: string,
@@ -122,142 +123,154 @@ export interface NodeQQNTWrapperUtil {
arg4: number,
): unknown;
checkNewUserDataSaveDirAvailable(arg0: string): unknown;
checkNewUserDataSaveDirAvailable (arg0: string): unknown;
copyUserData(arg0: string, arg1: string): Promise<unknown>;
copyUserData (arg0: string, arg1: string): Promise<unknown>;
setUserDataSaveDirectory(arg0: string): Promise<unknown>;
setUserDataSaveDirectory (arg0: string): Promise<unknown>;
hasOtherRunningQQProcess(): boolean;
hasOtherRunningQQProcess (): boolean;
quitAllRunningQQProcess(arg: boolean): unknown;
quitAllRunningQQProcess (arg: boolean): unknown;
checkNvidiaConfig(): unknown;
checkNvidiaConfig (): unknown;
repairNvidiaConfig(): unknown;
repairNvidiaConfig (): unknown;
getNvidiaDriverVersion(): unknown;
getNvidiaDriverVersion (): unknown;
isNull(): unknown;
isNull (): unknown;
createThumbnailImage (
serviceName: string,
filePath: string,
targetPath: string,
imgSize: {
width: number,
height: number;
},
fileFormat: string,
arg: number | null | undefined, // null undefined都行
): Promise<GeneralCallResult & { targetPath?: string; }>;
}
export interface NodeIQQNTStartupSessionWrapper {
create(): NodeIQQNTStartupSessionWrapper;
stop(): void;
start(): void;
createWithModuleList(uk: unknown): unknown;
getSessionIdList(): unknown;
create (): NodeIQQNTStartupSessionWrapper;
stop (): void;
start (): void;
createWithModuleList (uk: unknown): unknown;
getSessionIdList (): unknown;
}
export interface NodeIQQNTWrapperSession {
getNTWrapperSession(str: string): NodeIQQNTWrapperSession;
getNTWrapperSession (str: string): NodeIQQNTWrapperSession;
get(): NodeIQQNTWrapperSession;
get (): NodeIQQNTWrapperSession;
new(): NodeIQQNTWrapperSession;
create(): NodeIQQNTWrapperSession;
create (): NodeIQQNTWrapperSession;
init(
init (
wrapperSessionInitConfig: WrapperSessionInitConfig,
nodeIDependsAdapter: NodeIDependsAdapter,
nodeIDispatcherAdapter: NodeIDispatcherAdapter,
nodeIKernelSessionListener: NodeIKernelSessionListener,
): void;
startNT(session: number): void;
startNT (session: number): void;
startNT(): void;
startNT (): void;
getBdhUploadService(): unknown;
getBdhUploadService (): unknown;
getECDHService(): NodeIKernelECDHService;
getECDHService (): NodeIKernelECDHService;
getMsgService(): NodeIKernelMsgService;
getMsgService (): NodeIKernelMsgService;
getProfileService(): NodeIKernelProfileService;
getProfileService (): NodeIKernelProfileService;
getProfileLikeService(): NodeIKernelProfileLikeService;
getProfileLikeService (): NodeIKernelProfileLikeService;
getGroupService(): NodeIKernelGroupService;
getGroupService (): NodeIKernelGroupService;
getStorageCleanService(): NodeIKernelStorageCleanService;
getStorageCleanService (): NodeIKernelStorageCleanService;
getBuddyService(): NodeIKernelBuddyService;
getBuddyService (): NodeIKernelBuddyService;
getRobotService(): NodeIKernelRobotService;
getRobotService (): NodeIKernelRobotService;
getTicketService(): NodeIKernelTicketService;
getTicketService (): NodeIKernelTicketService;
getTipOffService(): NodeIKernelTipOffService;
getTipOffService (): NodeIKernelTipOffService;
getNodeMiscService(): NodeIKernelNodeMiscService;
getNodeMiscService (): NodeIKernelNodeMiscService;
getRichMediaService(): NodeIKernelRichMediaService;
getRichMediaService (): NodeIKernelRichMediaService;
getMsgBackupService(): NodeIKernelMsgBackupService;
getMsgBackupService (): NodeIKernelMsgBackupService;
getAlbumService(): NodeIKernelAlbumService;
getAlbumService (): NodeIKernelAlbumService;
getTianShuService(): NodeIKernelTianShuService;
getTianShuService (): NodeIKernelTianShuService;
getUnitedConfigService(): NodeIKernelUnitedConfigService;
getUnitedConfigService (): NodeIKernelUnitedConfigService;
getSearchService(): NodeIKernelSearchService;
getSearchService (): NodeIKernelSearchService;
getFlashTransferService(): NodeIKernelFlashTransferService;
getFlashTransferService (): NodeIKernelFlashTransferService;
getDirectSessionService(): unknown;
getDirectSessionService (): unknown;
getRDeliveryService(): unknown;
getRDeliveryService (): unknown;
getAvatarService(): NodeIKernelAvatarService;
getAvatarService (): NodeIKernelAvatarService;
getFeedChannelService(): unknown;
getFeedChannelService (): unknown;
getYellowFaceService(): unknown;
getYellowFaceService (): unknown;
getCollectionService(): NodeIKernelCollectionService;
getCollectionService (): NodeIKernelCollectionService;
getSettingService(): unknown;
getSettingService (): unknown;
getQiDianService(): unknown;
getQiDianService (): unknown;
getFileAssistantService(): unknown;
getFileAssistantService (): unknown;
getGuildService(): unknown;
getGuildService (): unknown;
getSkinService(): unknown;
getSkinService (): unknown;
getTestPerformanceService(): NodeIkernelTestPerformanceService;
getTestPerformanceService (): NodeIkernelTestPerformanceService;
getQQPlayService(): unknown;
getQQPlayService (): unknown;
getDbToolsService(): unknown;
getDbToolsService (): unknown;
getUixConvertService(): NodeIKernelUixConvertService;
getUixConvertService (): NodeIKernelUixConvertService;
getOnlineStatusService(): unknown;
getOnlineStatusService (): unknown;
getRemotingService(): unknown;
getRemotingService (): unknown;
getGroupTabService(): unknown;
getGroupTabService (): unknown;
getGroupSchoolService(): unknown;
getGroupSchoolService (): unknown;
getLiteBusinessService(): unknown;
getLiteBusinessService (): unknown;
getGuildMsgService(): unknown;
getGuildMsgService (): unknown;
getLockService(): unknown;
getLockService (): unknown;
getMSFService(): NodeIKernelMSFService;
getMSFService (): NodeIKernelMSFService;
getGuildHotUpdateService(): unknown;
getGuildHotUpdateService (): unknown;
getAVSDKService(): unknown;
getAVSDKService (): unknown;
getRecentContactService(): NodeIKernelRecentContactService;
getRecentContactService (): NodeIKernelRecentContactService;
getConfigMgrService(): unknown;
getConfigMgrService (): unknown;
}
export interface EnginInitDesktopConfig {
@@ -271,20 +284,20 @@ export interface EnginInitDesktopConfig {
global_path_config: {
desktopGlobalPath: string;
};
thumb_config: { maxSide: 324; minSide: 48; longLimit: 6; density: 2 };
thumb_config: { maxSide: 324; minSide: 48; longLimit: 6; density: 2; };
}
export interface NodeIQQNTWrapperEngine {
get(): NodeIQQNTWrapperEngine;
get (): NodeIQQNTWrapperEngine;
initWithDeskTopConfig(config: EnginInitDesktopConfig, nodeIGlobalAdapter: NodeIGlobalAdapter): void;
initWithDeskTopConfig (config: EnginInitDesktopConfig, nodeIGlobalAdapter: NodeIGlobalAdapter): void;
}
export interface WrapperNodeApi {
NodeIO3MiscService: NodeIO3MiscService;
NodeQQNTWrapperUtil: NodeQQNTWrapperUtil;
NodeIQQNTWrapperSession: NodeIQQNTWrapperSession;
NodeIQQNTStartupSessionWrapper: NodeIQQNTStartupSessionWrapper
NodeIQQNTStartupSessionWrapper: NodeIQQNTStartupSessionWrapper;
NodeIQQNTWrapperEngine: NodeIQQNTWrapperEngine;
NodeIKernelLoginService: NodeIKernelLoginService;
+20 -4
View File
@@ -5,9 +5,18 @@ import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
import { NetworkAdapterConfig } from '../config/config';
import { TSchema } from '@sinclair/typebox';
import { StreamPacket, StreamPacketBasic, StreamStatus } from './stream/StreamBasic';
export const ActionExamples = {
Common: {
errors: [
{ code: 1400, description: '请求参数错误或业务逻辑执行失败' },
{ code: 1401, description: '权限不足' },
{ code: 1404, description: '资源不存在' }
]
}
};
export class OB11Response {
private static createResponse<T>(data: T, status: string, retcode: number, message: string = '', echo: unknown = null, useStream: boolean = false): OB11Return<T> {
private static createResponse<T> (data: T, status: string, retcode: number, message: string = '', echo: unknown = null, useStream: boolean = false): OB11Return<T> {
return {
status,
retcode,
@@ -19,11 +28,11 @@ export class OB11Response {
};
}
static res<T>(data: T, status: string, retcode: number, message: string = '', echo: unknown = null, useStream: boolean = false): OB11Return<T> {
static res<T> (data: T, status: string, retcode: number, message: string = '', echo: unknown = null, useStream: boolean = false): OB11Return<T> {
return this.createResponse(data, status, retcode, message, echo, useStream);
}
static ok<T>(data: T, echo: unknown = null, useStream: boolean = false): OB11Return<T> {
static ok<T> (data: T, echo: unknown = null, useStream: boolean = false): OB11Return<T> {
return this.createResponse(data, 'ok', 0, '', echo, useStream);
}
@@ -32,15 +41,22 @@ export class OB11Response {
}
}
export abstract class OneBotRequestToolkit {
abstract send<T>(packet: StreamPacket<T>): Promise<void>;
abstract send<T> (packet: StreamPacket<T>): Promise<void>;
}
export abstract class OneBotAction<PayloadType, ReturnDataType> {
actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown;
core: NapCatCore;
private validate?: ValidateFunction<unknown> = undefined;
payloadSchema?: TSchema = undefined;
returnSchema?: TSchema = undefined;
payloadExample?: unknown = undefined;
returnExample?: unknown = undefined;
actionSummary: string = '';
actionDescription: string = '';
actionTags: string[] = [];
obContext: NapCatOneBot11Adapter;
useStream: boolean = false;
errorExamples: Array<{ code: number, description: string; }> = ActionExamples.Common.errors;
constructor (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.obContext = obContext;
@@ -0,0 +1,45 @@
export const ExtendsActionsExamples = {
OCRImage: {
payload: { image: 'image_id_123' },
response: { texts: [{ text: '识别内容', coordinates: [] }] },
},
GetAiCharacters: {
payload: { group_id: '123456' },
response: [
{
type: 'string',
characters: [
{ character_id: 'id', character_name: 'name', preview_url: 'url' }
]
}
],
},
GetClientkey: {
payload: {},
response: { clientkey: 'abcdef123456' },
},
SetQQAvatar: {
payload: { file: 'base64://...' },
response: null,
},
SetGroupKickMembers: {
payload: { group_id: '123456', user_id: ['123456789'], reject_add_request: false },
response: null,
},
TranslateEnWordToZn: {
payload: { words: ['hello'] },
response: { words: ['你好'] },
},
GetRkey: {
payload: {},
response: { rkey: '...' },
},
SetLongNick: {
payload: { longNick: '个性签名' },
response: null,
},
SetSpecialTitle: {
payload: { group_id: '123456', user_id: '123456789', special_title: '头衔' },
response: null,
},
};
@@ -0,0 +1,22 @@
export const FileActionsExamples = {
GetFile: {
payload: { file: 'file_id_123' },
response: { file: '/path/to/file', url: 'http://...', file_size: 1024, file_name: 'test.jpg' },
},
GetGroupFileUrl: {
payload: { group_id: '123456', file_id: 'file_id_123', busid: 102 },
response: { url: 'http://...' },
},
GetImage: {
payload: { file: 'image_id_123' },
response: { file: '/path/to/image', url: 'http://...' },
},
GetPrivateFileUrl: {
payload: { user_id: '123456789', file_id: 'file_id_123' },
response: { url: 'http://...' },
},
GetRecord: {
payload: { file: 'record_id_123', out_format: 'mp3' },
response: { file: '/path/to/record', url: 'http://...' },
},
};
@@ -0,0 +1,102 @@
export const GoCQHTTPActionsExamples = {
GetStrangerInfo: {
payload: { user_id: '123456789' },
response: { user_id: 123456789, nickname: '昵称', sex: 'unknown' },
},
GetGroupHonorInfo: {
payload: { group_id: '123456', type: 'all' },
response: { group_id: 123456, current_talkative: {}, talkative_list: [] },
},
GetForwardMsg: {
payload: { message_id: '123456' },
response: { messages: [] },
},
SendForwardMsg: {
payload: { group_id: '123456', messages: [] },
response: { message_id: 123456 },
},
GetGroupAtAllRemain: {
payload: { group_id: '123456' },
response: { can_at_all: true, remain_at_all_count_for_group: 10, remain_at_all_count_for_self: 10 },
},
CreateGroupFileFolder: {
payload: { group_id: '123456', name: '测试目录' },
response: { result: {}, groupItem: {} },
},
DeleteGroupFile: {
payload: { group_id: '123456', file_id: 'file_uuid_123' },
response: {},
},
DeleteGroupFileFolder: {
payload: { group_id: '123456', folder_id: 'folder_uuid_123' },
response: {},
},
DownloadFile: {
payload: { url: 'https://example.com/file.png', thread_count: 1, headers: 'User-Agent: NapCat' },
response: { file: '/path/to/downloaded/file' },
},
GetFriendMsgHistory: {
payload: { user_id: '123456789', message_seq: 0, count: 20 },
response: { messages: [] },
},
GetGroupFilesByFolder: {
payload: { group_id: '123456', folder_id: 'folder_id' },
response: { files: [], folders: [] },
},
GetGroupFileSystemInfo: {
payload: { group_id: '123456' },
response: { file_count: 10, limit_count: 10000, used_space: 1024, total_space: 10737418240 },
},
GetGroupMsgHistory: {
payload: { group_id: '123456', message_seq: 0, count: 20 },
response: { messages: [] },
},
GetGroupRootFiles: {
payload: { group_id: '123456' },
response: { files: [], folders: [] },
},
GetOnlineClient: {
payload: { no_cache: false },
response: [],
},
GoCQHTTPCheckUrlSafely: {
payload: { url: 'https://example.com' },
response: { level: 1 },
},
GoCQHTTPDeleteFriend: {
payload: { user_id: '123456789' },
response: {},
},
GoCQHTTPGetModelShow: {
payload: { model: 'iPhone 13' },
response: { variants: [] },
},
GoCQHTTPSetModelShow: {
payload: { model: 'iPhone 13', model_show: 'iPhone 13' },
response: {},
},
QuickAction: {
payload: { context: {}, operation: {} },
response: {},
},
SendGroupNotice: {
payload: { group_id: '123456', content: '公告内容', image: 'base64://...' },
response: {},
},
SetGroupPortrait: {
payload: { group_id: '123456', file: 'base64://...' },
response: { result: 0, errMsg: '' },
},
SetQQProfile: {
payload: { nickname: '新昵称', personal_note: '个性签名' },
response: {},
},
UploadGroupFile: {
payload: { group_id: '123456', file: '/path/to/file', name: 'test.txt' },
response: { file_id: 'file_uuid_123' },
},
UploadPrivateFile: {
payload: { user_id: '123456789', file: '/path/to/file', name: 'test.txt' },
response: { file_id: 'file_uuid_123' },
},
};
@@ -0,0 +1,79 @@
export const GroupActionsExamples = {
DelEssenceMsg: {
payload: { message_id: 123456 },
response: null,
},
DelGroupNotice: {
payload: { group_id: '123456', notice_id: 'notice_123' },
response: null,
},
GetGroupDetailInfo: {
payload: { group_id: '123456' },
response: { group_id: 123456, group_name: '测试群', member_count: 100, max_member_count: 500 },
},
GetGroupEssence: {
payload: { group_id: '123456' },
response: [{ message_id: 123456, sender_id: 123456, sender_nick: '昵称', operator_id: 123456, operator_nick: '昵称', operator_time: 1710000000, content: '精华内容' }],
},
GetGroupInfo: {
payload: { group_id: '123456' },
response: { group_id: 123456, group_name: '测试群', member_count: 100, max_member_count: 500 },
},
GetGroupList: {
payload: {},
response: [{ group_id: 123456, group_name: '测试群', member_count: 100, max_member_count: 500 }],
},
GetGroupMemberInfo: {
payload: { group_id: '123456', user_id: '123456789' },
response: { group_id: 123456, user_id: 123456789, nickname: '昵称', card: '名片', role: 'member' },
},
GetGroupMemberList: {
payload: { group_id: '123456' },
response: [{ group_id: 123456, user_id: 123456789, nickname: '昵称', card: '名片', role: 'member' }],
},
GetGroupNotice: {
payload: { group_id: '123456' },
response: [{ notice_id: 'notice_123', sender_id: 123456, publish_time: 1710000000, message: { text: '公告内容', image: [] } }],
},
SendGroupMsg: {
payload: { group_id: '123456', message: 'hello' },
response: { message_id: 123456 },
},
SetEssenceMsg: {
payload: { message_id: 123456 },
response: null,
},
SetGroupAddRequest: {
payload: { flag: 'flag_123', sub_type: 'add', approve: true },
response: null,
},
SetGroupAdmin: {
payload: { group_id: '123456', user_id: '123456789', enable: true },
response: null,
},
SetGroupBan: {
payload: { group_id: '123456', user_id: '123456789', duration: 1800 },
response: null,
},
SetGroupCard: {
payload: { group_id: '123456', user_id: '123456789', card: '新名片' },
response: null,
},
SetGroupKick: {
payload: { group_id: '123456', user_id: '123456789', reject_add_request: false },
response: null,
},
SetGroupLeave: {
payload: { group_id: '123456', is_dismiss: false },
response: null,
},
SetGroupName: {
payload: { group_id: '123456', group_name: '新群名' },
response: null,
},
SetGroupWholeBan: {
payload: { group_id: '123456', enable: true },
response: null,
},
};
@@ -0,0 +1,10 @@
export const GuildActionsExamples = {
GetGuildList: {
payload: {},
response: [{ guild_id: '123456', guild_name: '测试频道' }],
},
GetGuildProfile: {
payload: { guild_id: '123456' },
response: { guild_id: '123456', guild_name: '测试频道', guild_display_id: '123' },
},
};
@@ -0,0 +1,10 @@
export const NewActionsExamples = {
GetDoubtFriendsAddRequest: {
payload: { count: 10 },
response: [{ user_id: 123456789, nickname: '昵称', age: 20, sex: 'male', reason: '申请理由', flag: 'flag_123' }],
},
SetDoubtFriendsAddRequest: {
payload: { flag: 'flag_123', approve: true },
response: {},
},
};
@@ -0,0 +1,14 @@
export const PacketActionsExamples = {
GetPacketStatus: {
payload: {},
response: { status: 'ok' },
},
SendPoke: {
payload: { user_id: '123456789' },
response: {},
},
SetGroupTodo: {
payload: { group_id: '123456', message_id: '123456789' },
response: {},
},
};
@@ -0,0 +1,42 @@
export const SystemActionsExamples = {
CanSendImage: {
payload: {},
response: { yes: true },
},
CanSendRecord: {
payload: {},
response: { yes: true },
},
CleanCache: {
payload: {},
response: {},
},
GetCredentials: {
payload: {},
response: { cookies: '...', csrf_token: 123456789 },
},
GetCSRF: {
payload: {},
response: { token: 123456789 },
},
GetLoginInfo: {
payload: {},
response: { user_id: 123456789, nickname: '机器人' },
},
GetStatus: {
payload: {},
response: { online: true, good: true },
},
GetSystemMsg: {
payload: {},
response: { invited_requests: [], join_requests: [] },
},
GetVersionInfo: {
payload: {},
response: { app_name: 'NapCatQQ', app_version: '1.0.0', protocol_version: 'v11' },
},
SetRestart: {
payload: { delay: 0 },
response: {},
},
};
@@ -0,0 +1,38 @@
export const UserActionsExamples = {
GetCookies: {
payload: { domain: 'qun.qq.com' },
response: { cookies: 'p_skey=xxx; p_uin=o0123456789;' },
},
GetFriendList: {
payload: {},
response: [{ user_id: 123456789, nickname: '昵称', remark: '备注' }],
},
GetRecentContact: {
payload: { count: 10 },
response: [
{
lastestMsg: 'hello',
peerUin: '123456789',
remark: 'remark',
msgTime: '1710000000',
chatType: 1,
msgId: '12345',
sendNickName: 'nick',
sendMemberName: 'card',
peerName: 'name',
},
],
},
SendLike: {
payload: { user_id: '123456789', times: 10 },
response: {},
},
SetFriendAddRequest: {
payload: { flag: 'flag_123', approve: true, remark: '好友' },
response: {},
},
SetFriendRemark: {
payload: { user_id: '123456789', remark: '新备注' },
response: {},
},
};
@@ -1,8 +1,15 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '../OneBotAction';
import { Type } from '@sinclair/typebox';
export class BotExit extends OneBotAction<void, void> {
override actionName = ActionName.Exit;
override payloadSchema = Type.Void();
override returnSchema = Type.Void();
override actionSummary = '退出登录';
override actionTags = ['系统扩展'];
override payloadExample = {};
override returnExample = null;
async _handle () {
process.exit(0);
@@ -2,21 +2,36 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '../OneBotAction';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
bot_appid: Type.String(),
button_id: Type.String({ default: '' }),
callback_data: Type.String({ default: '' }),
msg_seq: Type.String({ default: '10086' }),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
bot_appid: Type.String({ description: '机器人AppID' }),
button_id: Type.String({ default: '', description: '按钮ID' }),
callback_data: Type.String({ default: '', description: '回调数据' }),
msg_seq: Type.String({ default: '10086', description: '消息序列号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class ClickInlineKeyboardButton extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '点击结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class ClickInlineKeyboardButton extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.ClickInlineKeyboardButton;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '点击内联键盘按钮';
override actionTags = ['消息扩展'];
override payloadExample = {
group_id: '123456',
bot_appid: '1234567890',
button_id: 'btn_1',
callback_data: '',
msg_seq: '10086'
};
override returnExample = {
};
async _handle (payload: PayloadType) {
return await this.core.apis.MsgApi.clickInlineKeyboardButton({
buttonId: payload.button_id,
peerId: payload.group_id.toString(),
@@ -2,18 +2,33 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const SchemaData = Type.Object({
rawData: Type.String(),
brief: Type.String(),
const PayloadSchema = Type.Object({
rawData: Type.String({ description: '原始数据' }),
brief: Type.String({ description: '简要描述' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class CreateCollection extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '创建结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class CreateCollection extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.CreateCollection;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '创建收藏';
override actionTags = ['扩展接口'];
override payloadExample = {
rawData: '收藏内容',
brief: '收藏标题'
};
override returnExample = {
result: 0,
errMsg: ''
};
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.CollectionApi.createCollection(
this.core.selfInfo.uin,
this.core.selfInfo.uid,
@@ -2,19 +2,34 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
album_id: Type.String(),
lloc: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
lloc: Type.String({ description: '媒体ID (lloc)' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class DelGroupAlbumMedia extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '删除结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class DelGroupAlbumMedia extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.DelGroupAlbumMedia;
override payloadSchema = SchemaData;
override actionSummary = '删除群相册媒体';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
lloc: 'media_id_1',
};
override returnExample = {
result: {}
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.WebApi.deleteAlbumMediaByNTQQ(
payload.group_id,
payload.album_id,
@@ -2,20 +2,32 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
album_id: Type.String(),
lloc: Type.String(),
content: Type.String(),
export const DoGroupAlbumCommentPayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册 ID' }),
lloc: Type.String({ description: '图片 ID' }),
content: Type.String({ description: '评论内容' }),
});
type Payload = Static<typeof SchemaData>;
export type DoGroupAlbumCommentPayload = Static<typeof DoGroupAlbumCommentPayloadSchema>;
export class DoGroupAlbumComment extends OneBotAction<Payload, unknown> {
export class DoGroupAlbumComment extends OneBotAction<DoGroupAlbumCommentPayload, any> {
override actionName = ActionName.DoGroupAlbumComment;
override payloadSchema = SchemaData;
override actionSummary = '发表群相册评论';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
lloc: 'media_id_1',
content: '很有意思'
};
override returnExample = {
result: {}
};
override payloadSchema = DoGroupAlbumCommentPayloadSchema;
override returnSchema = Type.Any({ description: '评论结果' });
async _handle (payload: Payload) {
async _handle (payload: DoGroupAlbumCommentPayload) {
return await this.core.apis.WebApi.doAlbumMediaPlainCommentByNTQQ(
payload.group_id,
payload.album_id,
@@ -2,18 +2,32 @@ import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
const SchemaData = Type.Object({
count: Type.Union([Type.Number(), Type.String()], { default: 48 }),
const PayloadSchema = Type.Object({
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class FetchCustomFace extends OneBotAction<Payload, string[]> {
const ReturnSchema = Type.Array(Type.String(), { description: '表情URL列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.FetchCustomFace;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取自定义表情';
override actionTags = ['系统扩展'];
override payloadExample = {
count: 10
};
override returnExample = [
'http://example.com/face1.png'
];
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
return ret.emojiInfoList.map(e => e.url);
}
}
@@ -2,29 +2,68 @@ import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { type NTQQMsgApi } from 'napcat-core/apis';
const SchemaData = Type.Object({
message_id: Type.Union([Type.Number(), Type.String()]),
emojiId: Type.Union([Type.Number(), Type.String()]),
emojiType: Type.Union([Type.Number(), Type.String()]),
count: Type.Union([Type.Number(), Type.String()], { default: 20 }),
cookie: Type.String({ default: '' })
const PayloadSchema = Type.Object({
message_id: Type.Union([Type.Number(), Type.String()], { description: '消息ID' }),
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' })
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class FetchEmojiLike extends OneBotAction<Payload, Awaited<ReturnType<NTQQMsgApi['getMsgEmojiLikesList']>>> {
const ReturnSchema = Type.Object({
emojiLikesList: Type.Array(Type.Object({
tinyId: Type.String({ description: 'TinyID' }),
nickName: Type.String({ description: '昵称' }),
headUrl: Type.String({ description: '头像URL' }),
}), { description: '表情回应列表' }),
cookie: Type.String({ description: '分页Cookie' }),
isLastPage: Type.Boolean({ description: '是否最后一页' }),
isFirstPage: Type.Boolean({ description: '是否第一页' }),
result: Type.Number({ description: '结果状态码' }),
errMsg: Type.String({ description: '错 误信息' }),
}, { description: '表情回应详情' });
type ReturnType = Static<typeof ReturnSchema>;
export class FetchEmojiLike extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.FetchEmojiLike;
override payloadSchema = SchemaData;
override actionSummary = '获取表情点赞详情';
override actionTags = ['消息扩展'];
override payloadExample = {
message_id: 12345,
emojiId: '123',
emojiType: 1,
count: 10,
cookie: ''
};
override returnExample = {
emojiLikesList: [
{
tinyId: '123456',
nickName: '测试用户',
headUrl: 'http://example.com/avatar.png'
}
],
cookie: '',
isLastPage: true,
isFirstPage: true,
result: 0,
errMsg: ''
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType): Promise<ReturnType> {
const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
if (!msgIdPeer) throw new Error('消息不存在');
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0];
if (!msg) throw new Error('消息不存在');
return await this.core.apis.MsgApi.getMsgEmojiLikesList(
const res = await this.core.apis.MsgApi.getMsgEmojiLikesList(
msgIdPeer.Peer, msg.msgSeq, payload.emojiId.toString(), payload.emojiType.toString(), payload.cookie, +payload.count
);
return res;
}
}
@@ -1,30 +1,46 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { AIVoiceChatType } from 'napcat-core/packet/entities/aiChat';
import { Type, Static } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
chat_type: Type.Union([Type.Union([Type.Number(), Type.String()])], { default: 1 }),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
chat_type: Type.Union([Type.Number(), Type.String()], { default: 1, description: '聊天类型' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface GetAiCharactersResponse {
type: string;
characters: {
character_id: string;
character_name: string;
preview_url: string;
}[];
}
const ReturnSchema = Type.Array(
Type.Object({
type: Type.String({ description: '角色类型' }),
characters: Type.Array(
Type.Object({
character_id: Type.String({ description: '角色ID' }),
character_name: Type.String({ description: '角色名称' }),
preview_url: Type.String({ description: '预览URL' }),
}),
{ description: '角色列表' }
),
}),
{ description: 'AI角色列表' }
);
export class GetAiCharacters extends GetPacketStatusDepends<Payload, GetAiCharactersResponse[]> {
type ReturnType = Static<typeof ReturnSchema>;
export class GetAiCharacters extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.GetAiCharacters;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取AI角色列表';
override actionDescription = '获取群聊中的AI角色列表';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.GetAiCharacters.payload;
override returnExample = ExtendsActionsExamples.GetAiCharacters.response;
async _handle (payload: Payload) {
const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, +payload.chat_type as AIVoiceChatType);
async _handle (payload: PayloadType) {
const chatTypeNum = Number(payload.chat_type);
const rawList = await this.core.apis.PacketApi.pkt.operation.FetchAiVoiceList(+payload.group_id, chatTypeNum);
return rawList?.map((item) => ({
type: item.category,
characters: item.voices.map((voice) => ({
@@ -1,12 +1,24 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '../OneBotAction';
import { Type, Static } from '@sinclair/typebox';
interface GetClientkeyResponse {
clientkey?: string;
}
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
export class GetClientkey extends OneBotAction<void, GetClientkeyResponse> {
const ReturnSchema = Type.Object({
clientkey: Type.Optional(Type.String({ description: '客户端Key' })),
}, { description: '获取ClientKey结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetClientkey extends OneBotAction<void, ReturnType> {
override actionName = ActionName.GetClientkey;
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
override actionSummary = '获取ClientKey';
override actionDescription = '获取当前登录帐号的ClientKey';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.GetClientkey.payload;
override returnExample = ExtendsActionsExamples.GetClientkey.response;
async _handle () {
return { clientkey: (await this.core.apis.UserApi.forceFetchClientKey()).clientKey };
@@ -1,20 +1,81 @@
import { type NTQQCollectionApi } from 'napcat-core/apis/collection';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const SchemaData = Type.Object({
category: Type.Union([Type.Number(), Type.String()]),
count: Type.Union([Type.Union([Type.Number(), Type.String()])], { default: 1 }),
const PayloadSchema = Type.Object({
category: Type.String({ description: '分类ID' }),
count: Type.String({ default: '50', description: '获取数量' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetCollectionList extends OneBotAction<Payload, Awaited<ReturnType<NTQQCollectionApi['getAllCollection']>>> {
const ReturnSchema = Type.Any({ description: '收藏列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetCollectionList;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取收藏列表';
override actionTags = ['系统扩展'];
override payloadExample = {
category: '0',
count: '50'
};
override returnExample = {
errCode: 0,
errMsg: "",
collectionSearchList: {
collectionItemList: [
{
cid: "123456",
type: 8,
status: 1,
author: {
type: 2,
numId: "123456",
strId: "昵称",
groupId: "123456",
groupName: "群名",
uid: "123456"
},
bid: 1,
category: 1,
createTime: "1769169157000",
collectTime: "1769413477691",
modifyTime: "1769413477691",
sequence: "1769413476735",
shareUrl: "",
customGroupId: 0,
securityBeat: false,
summary: {
textSummary: null,
linkSummary: null,
gallerySummary: null,
audioSummary: null,
videoSummary: null,
fileSummary: null,
locationSummary: null,
richMediaSummary: {
title: "",
subTitle: "",
brief: "text",
picList: [],
contentType: 1,
originalUri: "",
publisher: "",
richMediaVersion: 0
}
}
}
],
hasMore: false,
bottomTimeStamp: "1769413477691"
}
};
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count);
}
}
@@ -0,0 +1,88 @@
import { Type, Static } from '@sinclair/typebox';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { Peer, ChatType } from '@/napcat-core';
const PayloadSchema = Type.Object({
group_id: Type.Optional(Type.String({ description: '群号,短ID可不传' })),
message_id: Type.String({ description: '消息ID,可以传递长ID或短ID' }),
emoji_id: Type.String({ description: '表情ID' }),
emoji_type: Type.Optional(Type.String({ description: '表情类型' })),
count: Type.Number({ default: 0, description: '数量,0代表全部' }),
});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
emoji_like_list: Type.Array(
Type.Object({
user_id: Type.String({ description: '点击者QQ号' }),
nick_name: Type.String({ description: '昵称?' }),
}),
{ description: '表情回应列表' }
),
});
type ReturnType = Static<typeof ReturnSchema>;
export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetEmojiLikes;
override actionSummary = '获取消息表情点赞列表';
override actionTags = ['消息扩展'];
override payloadExample = {
message_id: '12345',
emoji_id: '123'
};
override returnExample = {
emoji_like_list: [
{
user_id: '654321',
nick_name: '测试用户'
}
]
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
let peer: Peer;
let msgId: string;
if (MessageUnique.isShortId(payload.message_id)) {
const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id);
if (!msgIdPeer) throw new Error('消息不存在');
peer = msgIdPeer.Peer;
msgId = msgIdPeer.MsgId;
} else {
if (!payload.group_id) throw new Error('长ID模式下必须提供群号');
peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id };
msgId = payload.message_id;
}
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgId])).msgList[0];
if (!msg) throw new Error('消息不存在');
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);
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
);
if (Array.isArray(res.emojiLikesList)) {
for (const like of res.emojiLikesList) {
emojiLikeList.push({ user_id: like.tinyId, nick_name: like.nickName });
}
}
if (res.isLastPage || !res.cookie) break;
cookie = res.cookie;
}
// 切断多余部分
if (payload.count > 0) {
emojiLikeList.splice(payload.count);
}
return { emoji_like_list: emojiLikeList };
}
}
@@ -1,12 +1,40 @@
import { OB11Construct } from '@/napcat-onebot/helper/data';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
import { OB11UserSchema } from '../schemas';
export class GetFriendWithCategory extends OneBotAction<void, unknown> {
const ReturnSchema = Type.Array(
Type.Object({
categoryId: Type.Number({ description: '分组ID' }),
categoryName: Type.String({ description: '分组名称' }),
categoryMbCount: Type.Number({ description: '分组内好友数量' }),
buddyList: Type.Array(OB11UserSchema, { description: '好友列表' }),
}),
{ description: '带分组的好友列表' }
);
type ReturnType = Static<typeof ReturnSchema>;
export class GetFriendWithCategory extends OneBotAction<void, ReturnType> {
override actionName = ActionName.GetFriendsWithCategory;
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
override actionSummary = '获取带分组的好友列表';
override actionTags = ['用户扩展'];
override payloadExample = {};
override returnExample = [
{
categoryId: 1,
categoryName: '我的好友',
categoryMbCount: 1,
buddyList: []
}
];
async _handle () {
return (await this.core.apis.FriendApi.getBuddyV2ExWithCate()).map(category => ({
const categories = await this.core.apis.FriendApi.getBuddyV2ExWithCate();
return categories.map(category => ({
...category,
buddyList: OB11Construct.friends(category.buddyList),
}));
@@ -1,16 +1,51 @@
import { GroupNotifyMsgStatus } from 'napcat-core';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Notify } from '@/napcat-onebot/types';
import { Type, Static } from '@sinclair/typebox';
export default class GetGroupAddRequest extends OneBotAction<null, Notify[] | null> {
const ReturnSchema = Type.Array(
Type.Object({
request_id: Type.Number({ description: '请求ID' }),
invitor_uin: Type.Number({ description: '邀请者QQ' }),
invitor_nick: Type.Optional(Type.String({ description: '邀请者昵称' })),
group_id: Type.Number({ description: '群号' }),
message: Type.Optional(Type.String({ description: '验证信息' })),
group_name: Type.Optional(Type.String({ description: '群名称' })),
checked: Type.Boolean({ description: '是否已处理' }),
actor: Type.Number({ description: '处理者QQ' }),
requester_nick: Type.Optional(Type.String({ description: '请求者昵称' })),
}),
{ description: '群通知列表' }
);
type ReturnType = Static<typeof ReturnSchema>;
export default class GetGroupAddRequest extends OneBotAction<void, ReturnType> {
override actionName = ActionName.GetGroupIgnoreAddRequest;
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
override actionSummary = '获取群被忽略的加群请求';
override actionTags = ['群组接口'];
override payloadExample = {};
override returnExample = [
{
request_id: 12345,
invitor_uin: 123456789,
invitor_nick: '邀请者',
group_id: 123456789,
message: '加群请求',
group_name: '群名称',
checked: false,
actor: 0,
requester_nick: '请求者'
}
];
async _handle (): Promise<Notify[] | null> {
async _handle (): Promise<ReturnType> {
const NTQQUserApi = this.core.apis.UserApi;
const NTQQGroupApi = this.core.apis.GroupApi;
const ignoredNotifies = await NTQQGroupApi.getSingleScreenNotifies(true, 10);
const retData: Notify[] = [];
const retData: ReturnType = [];
const notifyPromises = ignoredNotifies
.filter(notify => notify.type === 7)
@@ -2,19 +2,35 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
album_id: Type.String(),
attach_info: Type.String({ default: '' }),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
attach_info: Type.String({ default: '', description: '附加信息(用于分页)' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetGroupAlbumMediaList extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '相册媒体列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupAlbumMediaList extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupAlbumMediaList;
override payloadSchema = SchemaData;
override actionSummary = '获取群相册媒体列表';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
};
override returnExample = {
media_list: [
{ media_id: 'media_id_1', url: 'http://example.com/1.jpg' }
]
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.WebApi.getAlbumMediaListByNTQQ(
payload.group_id,
payload.album_id,
@@ -1,17 +1,30 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetGroupInfoEx extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '群扩展信息' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupInfoEx extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupInfoEx;
override payloadSchema = SchemaData;
override actionSummary = '获取群详细信息 (扩展)';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456'
};
override returnExample = {
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return (await this.core.apis.GroupApi.getGroupExtFE0Info([payload.group_id.toString()])).result.groupExtInfos.get(payload.group_id.toString());
}
}
@@ -1,57 +1,79 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { MiniAppInfo, MiniAppInfoHelper } from 'napcat-core/packet/utils/helper/miniAppHelper';
import { MiniAppData, MiniAppRawData, MiniAppReqCustomParams, MiniAppReqParams } from 'napcat-core/packet/entities/miniApp';
import { MiniAppReqCustomParams, MiniAppReqParams } from 'napcat-core/packet/entities/miniApp';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Union([
const PayloadSchema = Type.Union([
Type.Object({
type: Type.Union([Type.Literal('bili'), Type.Literal('weibo')]),
title: Type.String(),
desc: Type.String(),
picUrl: Type.String(),
jumpUrl: Type.String(),
webUrl: Type.Optional(Type.String()),
rawArkData: Type.Optional(Type.Union([Type.String()])),
type: Type.Union([Type.Literal('bili'), Type.Literal('weibo')], { description: '模板类型' }),
title: Type.String({ description: '标题' }),
desc: Type.String({ description: '描述' }),
picUrl: Type.String({ description: '图片URL' }),
jumpUrl: Type.String({ description: '跳转URL' }),
webUrl: Type.Optional(Type.String({ description: '网页URL' })),
rawArkData: Type.Optional(Type.Union([Type.String()], { description: '是否返回原始Ark数据' })),
}),
Type.Object({
title: Type.String(),
desc: Type.String(),
picUrl: Type.String(),
jumpUrl: Type.String(),
iconUrl: Type.String(),
webUrl: Type.Optional(Type.String()),
appId: Type.String(),
scene: Type.Union([Type.Number(), Type.String()]),
templateType: Type.Union([Type.Number(), Type.String()]),
businessType: Type.Union([Type.Number(), Type.String()]),
verType: Type.Union([Type.Number(), Type.String()]),
shareType: Type.Union([Type.Number(), Type.String()]),
versionId: Type.String(),
sdkId: Type.String(),
withShareTicket: Type.Union([Type.Number(), Type.String()]),
rawArkData: Type.Optional(Type.Union([Type.String()])),
title: Type.String({ description: '标题' }),
desc: Type.String({ description: '描述' }),
picUrl: Type.String({ description: '图片URL' }),
jumpUrl: Type.String({ description: '跳转URL' }),
iconUrl: Type.String({ description: '图标URL' }),
webUrl: Type.Optional(Type.String({ description: '网页URL' })),
appId: Type.String({ description: '小程序AppID' }),
scene: Type.String({ description: '场景ID' }),
templateType: Type.String({ description: '模板类型' }),
businessType: Type.String({ description: '业务类型' }),
verType: Type.String({ description: '版本类型' }),
shareType: Type.String({ description: '分享类型' }),
versionId: Type.String({ description: '版本ID' }),
sdkId: Type.String({ description: 'SDK ID' }),
withShareTicket: Type.String({ description: '是否携带分享票据' }),
rawArkData: Type.Optional(Type.String({ description: '是否返回原始Ark数据' })),
}),
]);
type Payload = Static<typeof SchemaData>;
], { description: '小程序Ark参数' });
export class GetMiniAppArk extends GetPacketStatusDepends<Payload, {
data: MiniAppData | MiniAppRawData
}> {
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
data: Type.Any({ description: 'Ark数据' }),
}, { description: '获取小程序Ark结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetMiniAppArk extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.GetMiniAppArk;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema; override actionSummary = '获取小程序 Ark';
override actionTags = ['系统扩展'];
override payloadExample = {
type: 'bili',
title: '测试标题',
desc: '测试描述',
picUrl: 'http://example.com/pic.jpg',
jumpUrl: 'http://example.com'
};
override returnExample = {
data: {
ark: 'ark_content'
}
};
async _handle (payload: PayloadType) {
let reqParam: MiniAppReqParams;
const customParams = {
const customParams: MiniAppReqCustomParams = {
title: payload.title,
desc: payload.desc,
picUrl: payload.picUrl,
jumpUrl: payload.jumpUrl,
webUrl: payload.webUrl,
} as MiniAppReqCustomParams;
webUrl: payload.webUrl ?? '',
};
if ('type' in payload) {
reqParam = MiniAppInfoHelper.generateReq(customParams, MiniAppInfo.get(payload.type)!.template);
const template = MiniAppInfo.get(payload.type)?.template;
if (!template) {
throw new Error('未知的模板类型');
}
reqParam = MiniAppInfoHelper.generateReq(customParams, template);
} else {
const { appId, scene, iconUrl, templateType, businessType, verType, shareType, versionId, withShareTicket } = payload;
reqParam = MiniAppInfoHelper.generateReq(
@@ -1,36 +1,65 @@
import { NTVoteInfo } from 'napcat-core';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
const SchemaData = Type.Object({
user_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
start: Type.Union([Type.Number(), Type.String()], { default: 0 }),
count: Type.Union([Type.Number(), Type.String()], { default: 10 }),
const PayloadSchema = Type.Object({
user_id: Type.Optional(Type.String({ description: 'QQ号' })),
start: Type.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' }),
count: Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetProfileLike extends OneBotAction<Payload, {
uid: string;
time: string;
favoriteInfo: {
userInfos: Array<NTVoteInfo>;
total_count: number;
last_time: number;
today_count: number;
};
voteInfo: {
total_count: number;
new_count: number;
new_nearby_count: number;
last_visit_time: number;
userInfos: Array<NTVoteInfo>;
};
}> {
const ReturnSchema = Type.Object({
uid: Type.String({ description: '用户UID' }),
time: Type.String({ description: '时间' }),
favoriteInfo: Type.Object({
userInfos: Type.Array(Type.Any(), { description: '点赞用户信息' }),
total_count: Type.Number({ description: '总点赞数' }),
last_time: Type.Number({ description: '最后点赞时间' }),
today_count: Type.Number({ description: '今日点赞数' }),
}),
voteInfo: Type.Object({
total_count: Type.Number({ description: '总点赞数' }),
new_count: Type.Number({ description: '新增点赞数' }),
new_nearby_count: Type.Number({ description: '新增附近点赞数' }),
last_visit_time: Type.Number({ description: '最后访问时间' }),
userInfos: Type.Array(Type.Any(), { description: '点赞用户信息' }),
}),
}, { description: '点赞详情' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetProfileLike extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetProfileLike;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取资料点赞';
override actionTags = ['用户扩展'];
override payloadExample = {
user_id: '123456789',
start: 0,
count: 10
};
override returnExample = {
uid: 'u_123',
time: '1734567890',
favoriteInfo: {
userInfos: [],
total_count: 10,
last_time: 1734567890,
today_count: 5
},
voteInfo: {
total_count: 100,
new_count: 2,
new_nearby_count: 0,
last_visit_time: 1734567890,
userInfos: []
}
};
async _handle (payload: PayloadType): Promise<ReturnType> {
const isSelf = this.core.selfInfo.uin === payload.user_id || !payload.user_id;
const userUid = isSelf || !payload.user_id ? this.core.selfInfo.uid : await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
const type = isSelf ? 2 : 1;
@@ -1,18 +1,37 @@
import { NTQQWebApi } from 'napcat-core/apis';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
import { NTQQWebApi } from 'napcat-core/apis';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetQunAlbumList extends OneBotAction<Payload, Awaited<ReturnType<NTQQWebApi['getAlbumListByNTQQ']>>['response']['album_list']> {
const ReturnSchema = Type.Array(Type.Any(), { description: '群相册列表' });
type GetQunAlbumListReturn = Awaited<globalThis.ReturnType<NTQQWebApi['getAlbumListByNTQQ']>>['response']['album_list'];
export class GetQunAlbumList extends OneBotAction<PayloadType, GetQunAlbumListReturn> {
override actionName = ActionName.GetQunAlbumList;
override payloadSchema = SchemaData;
override actionSummary = '获取群相册列表';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
};
override returnExample = [
{
album_id: 'album_1',
album_name: '测试相册',
cover_url: 'http://example.com/cover.jpg',
create_time: 1734567890
}
];
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType): Promise<GetQunAlbumListReturn> {
return (await this.core.apis.WebApi.getAlbumListByNTQQ(payload.group_id)).response.album_list;
}
}
@@ -1,8 +1,24 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Type, Static } from '@sinclair/typebox';
export class GetRkey extends GetPacketStatusDepends<void, Array<unknown>> {
const ReturnSchema = Type.Array(Type.Any(), { description: 'Rkey列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetRkey extends GetPacketStatusDepends<void, ReturnType> {
override actionName = ActionName.GetRkey;
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
override actionSummary = '获取 RKey';
override actionTags = ['系统扩展'];
override payloadExample = {};
override returnExample = [
{
"key": "rkey_value",
"expired": 1734567890
}
];
async _handle () {
return await this.core.apis.PacketApi.pkt.operation.FetchRkey();
@@ -1,8 +1,21 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type, Static } from '@sinclair/typebox';
export class GetRobotUinRange extends OneBotAction<void, Array<unknown>> {
const ReturnSchema = Type.Array(Type.Any(), { description: '机器人Uin范围列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetRobotUinRange extends OneBotAction<void, ReturnType> {
override actionName = ActionName.GetRobotUinRange;
override actionSummary = '获取机器人 UIN 范围';
override actionTags = ['系统扩展'];
override payloadExample = {};
override returnExample = [
{ minUin: '12345678', maxUin: '87654321' }
];
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
async _handle () {
return await this.core.apis.UserApi.getRobotUinRange();
@@ -2,26 +2,37 @@ import { PacketBuf } from 'napcat-core/packet/transformer/base';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { ProtoBuf, ProtoBufBase, PBUint32, PBString } from 'napcat.protobuf';
import { Type, Static } from '@sinclair/typebox';
interface Friend {
uin: number;
uid: string;
nick_name: string;
age: number;
source: string;
}
const ReturnSchema = Type.Array(
Type.Object({
uin: Type.Number({ description: 'QQ号' }),
uid: Type.String({ description: '用户UID' }),
nick_name: Type.String({ description: '昵称' }),
age: Type.Number({ description: '年龄' }),
source: Type.String({ description: '来源' }),
}),
{ description: '单向好友列表' }
);
interface Block {
str_uid: string;
bytes_source: string;
uint32_sex: number;
uint32_age: number;
bytes_nick: string;
uint64_uin: number;
}
type ReturnType = Static<typeof ReturnSchema>;
export class GetUnidirectionalFriendList extends OneBotAction<void, Friend[]> {
export class GetUnidirectionalFriendList extends OneBotAction<void, ReturnType> {
override actionName = ActionName.GetUnidirectionalFriendList;
override payloadSchema = Type.Void();
override returnSchema = ReturnSchema;
override actionSummary = '获取单向好友列表';
override actionTags = ['用户扩展'];
override payloadExample = {};
override returnExample = [
{
uin: 123456789,
uid: 'u_123',
nick_name: '单向好友',
age: 20,
source: '来源'
}
];
async pack_data (data: string): Promise<Uint8Array> {
return ProtoBuf(class extends ProtoBufBase {
@@ -30,7 +41,7 @@ export class GetUnidirectionalFriendList extends OneBotAction<void, Friend[]> {
}).encode();
}
async _handle (): Promise<Friend[]> {
async _handle (): Promise<ReturnType> {
const self_id = this.core.selfInfo.uin;
const req_json = {
uint64_uin: self_id,
@@ -40,10 +51,18 @@ export class GetUnidirectionalFriendList extends OneBotAction<void, Friend[]> {
};
const packed_data = await this.pack_data(JSON.stringify(req_json));
const data = Buffer.from(packed_data);
const rsq = { cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', data: data as PacketBuf };
const rsq = { cmd: 'MQUpdateSvc_com_qq_ti.web.OidbSvc.0xe17_0', data: data as unknown as PacketBuf };
const rsp_data = await this.core.apis.PacketApi.pkt.operation.sendPacket(rsq, true);
const block_json = ProtoBuf(class extends ProtoBufBase { data = PBString(4); }).decode(rsp_data);
const block_list: Block[] = JSON.parse(block_json.data).rpt_block_list;
interface BlockItem {
uint64_uin: number;
str_uid: string;
bytes_nick: string;
uint32_age: number;
bytes_source: string;
}
const block_data: { rpt_block_list: BlockItem[]; } = JSON.parse(block_json.data);
const block_list = block_data.rpt_block_list;
return block_list.map((block) => ({
uin: block.uint64_uin,
@@ -2,17 +2,38 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
user_id: Type.String({ description: 'QQ号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetUserStatus extends GetPacketStatusDepends<Payload, { status: number; ext_status: number; } | undefined> {
const ReturnSchema = Type.Object({
status: Type.Number({ description: '在线状态' }),
ext_status: Type.Number({ description: '扩展状态' }),
}, { description: '用户状态' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetUserStatus extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.GetUserStatus;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取用户在线状态';
override actionTags = ['系统扩展'];
override payloadExample = {
user_id: '123456789'
};
override returnExample = {
status: 10,
ext_status: 0
};
async _handle (payload: Payload) {
return await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id);
async _handle (payload: PayloadType) {
const res = await this.core.apis.PacketApi.pkt.operation.GetStrangerStatus(+payload.user_id);
if (!res) {
throw new Error('无法获取用户状态');
}
return res;
}
}
@@ -3,24 +3,38 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
current_parent_directory: Type.String(),
target_parent_directory: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
current_parent_directory: Type.String({ description: '当前父目录' }),
target_parent_directory: Type.String({ description: '目标父目录' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface MoveGroupFileResponse {
ok: boolean;
}
const ReturnSchema = Type.Object({
ok: Type.Boolean({ description: '是否成功' }),
}, { description: '移动文件结果' });
export class MoveGroupFile extends GetPacketStatusDepends<Payload, MoveGroupFileResponse> {
type ReturnType = Static<typeof ReturnSchema>;
export class MoveGroupFile extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.MoveGroupFile;
override payloadSchema = SchemaData;
override actionSummary = '移动群文件';
override actionTags = ['文件扩展'];
override payloadExample = {
group_id: '123456',
file_id: '/file_id',
current_parent_directory: '/current_folder_id',
target_parent_directory: '/target_folder_id',
};
override returnExample = {
ok: true
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
await this.core.apis.PacketApi.pkt.operation.MoveGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.target_parent_directory);
@@ -3,18 +3,29 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { checkFileExist, uriToLocalFile } from 'napcat-common/src/file';
import fs from 'fs';
import { Static, Type } from '@sinclair/typebox';
import { GeneralCallResultStatus } from 'napcat-core';
const SchemaData = Type.Object({
image: Type.String(),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
image: Type.String({ description: '图片路径、URL或Base64' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
class OCRImageBase extends OneBotAction<Payload, GeneralCallResultStatus> {
override payloadSchema = SchemaData;
const ReturnSchema = Type.Any({ description: 'OCR结果' });
async _handle (payload: Payload) {
type ReturnType = Static<typeof ReturnSchema>;
class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '图片 OCR 识别';
override actionDescription = '识别图片中的文字内容(仅Windows端支持)';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.OCRImage.payload;
override returnExample = ExtendsActionsExamples.OCRImage.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
if (!success) {
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
@@ -37,8 +48,10 @@ class OCRImageBase extends OneBotAction<Payload, GeneralCallResultStatus> {
export class OCRImage extends OCRImageBase {
override actionName = ActionName.OCRImage;
override actionSummary = '图片 OCR 识别';
}
export class IOCRImage extends OCRImageBase {
override actionName = ActionName.IOCRImage;
override actionSummary = '图片 OCR 识别 (内部)';
}
@@ -3,24 +3,38 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
current_parent_directory: Type.String(),
new_name: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
current_parent_directory: Type.String({ description: '当前父目录' }),
new_name: Type.String({ description: '新文件名' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface RenameGroupFileResponse {
ok: boolean;
}
const ReturnSchema = Type.Object({
ok: Type.Boolean({ description: '是否成功' }),
}, { description: '重命名文件结果' });
export class RenameGroupFile extends GetPacketStatusDepends<Payload, RenameGroupFileResponse> {
type ReturnType = Static<typeof ReturnSchema>;
export class RenameGroupFile extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.RenameGroupFile;
override payloadSchema = SchemaData;
override actionSummary = '重命名群文件';
override actionTags = ['文件扩展'];
override payloadExample = {
group_id: '123456',
file_id: '/file_id',
current_parent_directory: '/',
new_name: 'new_name.jpg'
};
override returnExample = {
ok: true
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
await this.core.apis.PacketApi.pkt.operation.RenameGroupFile(+payload.group_id, contextMsgFile.fileUUID, payload.current_parent_directory, payload.new_name);
@@ -3,20 +3,35 @@ import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketS
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
cmd: Type.String(),
data: Type.String(),
rsp: Type.Union([Type.String(), Type.Boolean()], { default: true }),
const PayloadSchema = Type.Object({
cmd: Type.String({ description: '命令字' }),
data: Type.String({ description: '十六进制数据' }),
rsp: Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SendPacket extends GetPacketStatusDepends<Payload, string | undefined> {
override payloadSchema = SchemaData;
const ReturnSchema = Type.Union([Type.String({ description: '响应十六进制数据' }), Type.Undefined()], { description: '发包结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SendPacket extends GetPacketStatusDepends<PayloadType, ReturnType> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionName = ActionName.SendPacket;
async _handle (payload: Payload) {
override actionSummary = '发送原始数据包';
override actionTags = ['系统扩展'];
override payloadExample = {
cmd: 'Example.Cmd',
data: '123456',
rsp: true
};
override returnExample = '123456';
async _handle (payload: PayloadType) {
const rsp = typeof payload.rsp === 'boolean' ? payload.rsp : payload.rsp === 'true';
const data = await this.core.apis.PacketApi.pkt.operation.sendPacket({ cmd: payload.cmd, data: Buffer.from(payload.data, 'hex') as PacketBuf }, rsp);
const packetData = Buffer.from(payload.data, 'hex') as unknown as PacketBuf;
const data = await this.core.apis.PacketApi.pkt.operation.sendPacket({ cmd: payload.cmd, data: packetData }, rsp);
return typeof data === 'object' ? data.toString('hex') : undefined;
}
}
@@ -2,19 +2,31 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
face_id: Type.Union([Type.Number(), Type.String()]), // 参考 face_config.json 的 QSid
face_type: Type.Union([Type.Number(), Type.String()], { default: '1' }),
wording: Type.String({ default: ' ' }),
const PayloadSchema = Type.Object({
face_id: Type.Union([Type.Number(), Type.String()], { description: '图标ID' }), // 参考 face_config.json 的 QSid
face_type: Type.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' }),
wording: Type.String({ default: ' ', description: '状态文字内容' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetDiyOnlineStatus extends OneBotAction<Payload, string> {
const ReturnSchema = Type.String({ description: '错误信息(如果有)' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetDiyOnlineStatus extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetDiyOnlineStatus;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema; override actionSummary = '设置自定义在线状态';
override actionDescription = '设置自定义在线状态';
override actionTags = ['用户扩展'];
override payloadExample = {
face_id: '123',
face_type: '1',
wording: '自定义状态'
};
override returnExample = '';
async _handle (payload: PayloadType) {
const ret = await this.core.apis.UserApi.setDiySelfOnlineStatus(
payload.face_id.toString(),
payload.wording,
@@ -2,19 +2,31 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
add_type: Type.Number(),
group_question: Type.Optional(Type.String()),
group_answer: Type.Optional(Type.String()),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
add_type: Type.Number({ description: '加群方式' }),
group_question: Type.Optional(Type.String({ description: '加群问题' })),
group_answer: Type.Optional(Type.String({ description: '加群答案' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetGroupAddOption extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '返回结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupAddOption extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupAddOption;
override payloadSchema = SchemaData;
async _handle (payload: Payload): Promise<null> {
override actionSummary = '设置群加群选项';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
add_type: 1,
};
override returnExample = null;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ret = await this.core.apis.GroupApi.setGroupAddOption(payload.group_id, {
addOption: payload.add_type,
groupQuestion: payload.group_question,
@@ -2,21 +2,37 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
album_id: Type.String(),
lloc: Type.String(),
id: Type.String(), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
set: Type.Boolean({ default: true }), // true=点赞 false=取消点赞 未实现
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
lloc: Type.String({ description: '媒体ID (lloc)' }),
id: Type.String({ description: '点赞ID' }), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
set: Type.Boolean({ default: true, description: '是否点赞' }), // true=点赞 false=取消点赞 未实现
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetGroupAlbumMediaLike extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '操作结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupAlbumMediaLike;
override payloadSchema = SchemaData;
override actionSummary = '点赞群相册媒体';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
lloc: 'media_id_1',
id: '123456',
};
override returnExample = {
result: {}
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
payload.group_id,
payload.album_id,
@@ -2,19 +2,31 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
user_id: Type.Array(Type.String()),
reject_add_request: Type.Optional(Type.Union([Type.Boolean(), Type.String()])),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
user_id: Type.Array(Type.String(), { description: 'QQ号列表' }),
reject_add_request: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { description: '是否拒绝加群请求' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetGroupKickMembers extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '返回结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupKickMembers extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupKickMembers;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '批量踢出群成员';
override actionDescription = '从指定群聊中批量踢出多个成员';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SetGroupKickMembers.payload;
override returnExample = ExtendsActionsExamples.SetGroupKickMembers.response;
async _handle (payload: Payload): Promise<null> {
async _handle (payload: PayloadType): Promise<ReturnType> {
const rejectReq = payload.reject_add_request?.toString() === 'true';
const uids: string[] = await Promise.all(payload.user_id.map(async uin => await this.core.apis.UserApi.getUidByUinV2(uin)));
await this.core.apis.GroupApi.kickMember(payload.group_id.toString(), uids.filter(uid => !!uid), rejectReq);
@@ -2,17 +2,31 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
remark: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
remark: Type.String({ description: '备注' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetGroupRemark extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '返回结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupRemark extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupRemark;
override payloadSchema = SchemaData;
async _handle (payload: Payload): Promise<null> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置群备注';
override actionDescription = '设置群备注';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
remark: '测试群备注'
};
override returnExample = null;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ret = await this.core.apis.GroupApi.setGroupRemark(payload.group_id, payload.remark);
if (ret.result !== 0) {
throw new Error(`设置群备注失败, ${ret.result}:${ret.errMsg}`);
@@ -2,18 +2,29 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
robot_member_switch: Type.Optional(Type.Number()),
robot_member_examine: Type.Optional(Type.Number()),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
robot_member_switch: Type.Optional(Type.Number({ description: '机器人成员开关' })),
robot_member_examine: Type.Optional(Type.Number({ description: '机器人成员审核' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetGroupRobotAddOption extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '返回结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupRobotAddOption extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupRobotAddOption;
override payloadSchema = SchemaData;
async _handle (payload: Payload): Promise<null> {
override actionSummary = '设置群机器人加群选项';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456'
};
override returnExample = null;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ret = await this.core.apis.GroupApi.setGroupRobotAddOption(
payload.group_id,
payload.robot_member_switch,
@@ -2,18 +2,29 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.String(),
no_code_finger_open: Type.Optional(Type.Number()),
no_finger_open: Type.Optional(Type.Number()),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
no_code_finger_open: Type.Optional(Type.Number({ description: '未知' })),
no_finger_open: Type.Optional(Type.Number({ description: '未知' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetGroupSearch extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '返回结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetGroupSearch extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetGroupSearch;
override payloadSchema = SchemaData;
async _handle (payload: Payload): Promise<null> {
override actionSummary = '设置群搜索选项';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456'
};
override returnExample = null;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType): Promise<ReturnType> {
const ret = await this.core.apis.GroupApi.setGroupSearch(payload.group_id, {
noCodeFingerOpenFlag: payload.no_code_finger_open,
noFingerOpenFlag: payload.no_finger_open,
@@ -2,16 +2,27 @@ import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketS
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
class SetGroupSignBase extends GetPacketStatusDepends<Payload, void> {
override payloadSchema = SchemaData;
const ReturnSchema = Type.Void({ description: '打卡结果' });
async _handle (payload: Payload) {
type ReturnType = Static<typeof ReturnSchema>;
class SetGroupSignBase extends GetPacketStatusDepends<PayloadType, ReturnType> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '群打卡';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456789'
};
override returnExample = null;
async _handle (payload: PayloadType) {
return await this.core.apis.PacketApi.pkt.operation.GroupSign(+payload.group_id);
}
}
@@ -3,17 +3,30 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { ChatType } from 'napcat-core';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
event_type: Type.Number(),
const PayloadSchema = Type.Object({
user_id: Type.String({ description: 'QQ号' }),
event_type: Type.Number({ description: '事件类型' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetInputStatus extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '设置结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetInputStatus extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetInputStatus;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置输入状态';
override actionTags = ['系统扩展'];
override payloadExample = {
user_id: '123456789',
event_type: 1
};
override returnExample = null;
async _handle (payload: PayloadType) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('uid is empty');
const peer = {
@@ -2,17 +2,29 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
longNick: Type.String(),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
longNick: Type.String({ description: '签名内容' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetLongNick extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '设置结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetLongNick extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetLongNick;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置个性签名';
override actionDescription = '修改当前登录帐号的个性签名';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SetLongNick.payload;
override returnExample = ExtendsActionsExamples.SetLongNick.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
return await this.core.apis.UserApi.setLongNick(payload.longNick);
}
}
@@ -2,19 +2,33 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
status: Type.Union([Type.Number(), Type.String()]),
ext_status: Type.Union([Type.Number(), Type.String()]),
battery_status: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
status: Type.Union([Type.Number(), Type.String()], { description: '在线状态' }),
ext_status: Type.Union([Type.Number(), Type.String()], { description: '扩展状态' }),
battery_status: Type.Union([Type.Number(), Type.String()], { description: '电量状态' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetOnlineStatus extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '设置结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetOnlineStatus extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetOnlineStatus;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置在线状态';
override actionDescription = statusText;
override actionTags = ['系统扩展'];
override payloadExample = {
status: 11,
ext_status: 0,
battery_status: 100
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const ret = await this.core.apis.UserApi.setSelfOnlineStatus(
+payload.status,
+payload.ext_status,
@@ -26,3 +40,216 @@ export class SetOnlineStatus extends OneBotAction<Payload, null> {
return null;
}
}
const statusText = `
## 状态列表
### 在线
\`\`\`json5;
{ "status": 10, "ext_status": 0, "battery_status": 0; }
\`\`\`
### Q我吧
\`\`\`json5;
{ "status": 60, "ext_status": 0, "battery_status": 0; }
\`\`\`
### 离开
\`\`\`json5;
{ "status": 30, "ext_status": 0, "battery_status": 0; }
\`\`\`
### 忙碌
\`\`\`json5;
{ "status": 50, "ext_status": 0, "battery_status": 0; }
\`\`\`
### 请勿打扰
\`\`\`json5;
{ "status": 70, "ext_status": 0, "battery_status": 0; }
\`\`\`
### 隐身
\`\`\`json5;
{ "status": 40, "ext_status": 0, "battery_status": 0; }
\`\`\`
### 听歌中
\`\`\`json5;
{ "status": 10, "ext_status": 1028, "battery_status": 0; }
\`\`\`
### 春日限定
\`\`\`json5;
{ "status": 10, "ext_status": 2037, "battery_status": 0; }
\`\`\`
### 一起元梦
\`\`\`json5;
{ "status": 10, "ext_status": 2025, "battery_status": 0; }
\`\`\`
### 求星搭子
\`\`\`json5;
{ "status": 10, "ext_status": 2026, "battery_status": 0; }
\`\`\`
### 被掏空
\`\`\`json5;
{ "status": 10, "ext_status": 2014, "battery_status": 0; }
\`\`\`
### 今日天气
\`\`\`json5;
{ "status": 10, "ext_status": 1030, "battery_status": 0; }
\`\`\`
### 我crash了
\`\`\`json5;
{ "status": 10, "ext_status": 2019, "battery_status": 0; }
\`\`\`
### 爱你
\`\`\`json5;
{ "status": 10, "ext_status": 2006, "battery_status": 0; }
\`\`\`
### 恋爱中
\`\`\`json5;
{ "status": 10, "ext_status": 1051, "battery_status": 0; }
\`\`\`
### 好运锦鲤
\`\`\`json5;
{ "status": 10, "ext_status": 1071, "battery_status": 0; }
\`\`\`
### 水逆退散
\`\`\`json5;
{ "status": 10, "ext_status": 1201, "battery_status": 0; }
\`\`\`
### 嗨到飞起
\`\`\`json5;
{ "status": 10, "ext_status": 1056, "battery_status": 0; }
\`\`\`
### 元气满满
\`\`\`json5;
{ "status": 10, "ext_status": 1058, "battery_status": 0; }
\`\`\`
### 宝宝认证
\`\`\`json5;
{ "status": 10, "ext_status": 1070, "battery_status": 0; }
\`\`\`
### 一言难尽
\`\`\`json5;
{ "status": 10, "ext_status": 1063, "battery_status": 0; }
\`\`\`
### 难得糊涂
\`\`\`json5;
{ "status": 10, "ext_status": 2001, "battery_status": 0; }
\`\`\`
### emo中
\`\`\`json5;
{ "status": 10, "ext_status": 1401, "battery_status": 0; }
\`\`\`
### 我太难了
\`\`\`json5;
{ "status": 10, "ext_status": 1062, "battery_status": 0; }
\`\`\`
### 我想开了
\`\`\`json5;
{ "status": 10, "ext_status": 2013, "battery_status": 0; }
\`\`\`
### 我没事
\`\`\`json5;
{ "status": 10, "ext_status": 1052, "battery_status": 0; }
\`\`\`
### 想静静
\`\`\`json5;
{ "status": 10, "ext_status": 1061, "battery_status": 0; }
\`\`\`
### 悠哉哉
\`\`\`json5;
{ "status": 10, "ext_status": 1059, "battery_status": 0; }
\`\`\`
### 去旅行
\`\`\`json5;
{ "status": 10, "ext_status": 2015, "battery_status": 0; }
\`\`\`
### 信号弱
\`\`\`json5;
{ "status": 10, "ext_status": 1011, "battery_status": 0; }
\`\`\`
### 出去浪
\`\`\`json5;
{ "status": 10, "ext_status": 2003, "battery_status": 0; }
\`\`\`
### 肝作业
\`\`\`json5;
{ "status": 10, "ext_status": 2012, "battery_status": 0; }
\`\`\`
### 学习中
\`\`\`json5;
{ "status": 10, "ext_status": 1018, "battery_status": 0; }
\`\`\`
### 搬砖中
\`\`\`json5;
{ "status": 10, "ext_status": 2023, "battery_status": 0; }
\`\`\`
### 摸鱼中
\`\`\`json5;
{ "status": 10, "ext_status": 1300, "battery_status": 0; }
\`\`\`
### 无聊中
\`\`\`json5;
{ "status": 10, "ext_status": 1060, "battery_status": 0; }
\`\`\`
### timi中
\`\`\`json5;
{ "status": 10, "ext_status": 1027, "battery_status": 0; }
\`\`\`
### 睡觉中
\`\`\`json5;
{ "status": 10, "ext_status": 1016, "battery_status": 0; }
\`\`\`
### 熬夜中
\`\`\`json5;
{ "status": 10, "ext_status": 1032, "battery_status": 0; }
\`\`\`
### 追剧中
\`\`\`json5;
{ "status": 10, "ext_status": 1021, "battery_status": 0; }
\`\`\`
### 我的电量
\`\`\`json5;
{
"status": 10,
"ext_status": 1000,
"battery_status": 0;
}
\`\`\`
`;
@@ -4,16 +4,29 @@ import fs from 'node:fs/promises';
import { checkFileExist, uriToLocalFile } from 'napcat-common/src/file';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
file: Type.String(),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
file: Type.String({ description: '图片路径、URL或Base64' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class SetAvatar extends OneBotAction<Payload, null> {
const ReturnSchema = Type.Null({ description: '设置结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.SetQQAvatar;
override payloadSchema = SchemaData;
async _handle (payload: Payload): Promise<null> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置QQ头像';
override actionDescription = '修改当前账号的QQ头像';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SetQQAvatar.payload;
override returnExample = ExtendsActionsExamples.SetQQAvatar.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
if (!success) {
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
@@ -26,7 +39,7 @@ export default class SetAvatar extends OneBotAction<Payload, null> {
throw new Error(`头像${payload.file}设置失败,api无返回`);
}
// log(`头像设置返回:${JSON.stringify(ret)}`)
if (ret.result as number === 1004022) {
if (Number(ret.result) === 1004022) {
throw new Error(`头像${payload.file}设置失败,文件可能不是图片格式`);
} else if (ret.result !== 0) {
throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`);
@@ -2,19 +2,31 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
user_id: Type.Union([Type.Number(), Type.String()]),
special_title: Type.String({ default: '' }),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
user_id: Type.String({ description: 'QQ号' }),
special_title: Type.String({ default: '', description: '专属头衔' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SetSpecialTitle extends GetPacketStatusDepends<Payload, void> {
const ReturnSchema = Type.Void({ description: '设置结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class SetSpecialTitle extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.SetSpecialTitle;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置专属头衔';
override actionDescription = '设置群聊中指定成员的专属头衔';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.SetSpecialTitle.payload;
override returnExample = ExtendsActionsExamples.SetSpecialTitle.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
await this.core.apis.PacketApi.pkt.operation.SetGroupSpecialTitle(+payload.group_id, uid, payload.special_title);
@@ -1,24 +1,35 @@
import { GeneralCallResult } from 'napcat-core';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
user_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
group_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
phone_number: Type.String({ default: '' }),
const PayloadSchema = Type.Object({
user_id: Type.Optional(Type.String({ description: 'QQ号' })),
group_id: Type.Optional(Type.String({ description: '群号' })),
phone_number: Type.String({ default: '', description: '手机号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class SharePeerBase extends OneBotAction<Payload, GeneralCallResult & {
arkMsg?: string;
arkJson?: string;
}> {
const ReturnSchema = Type.Any({ description: '分享结果' });
override payloadSchema = SchemaData;
type ReturnType = Static<typeof ReturnSchema>;
async _handle (payload: Payload) {
export class SharePeerBase extends OneBotAction<PayloadType, ReturnType> {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '分享用户 (Ark)';
override actionDescription = '获取用户推荐的 Ark 内容';
override actionTags = ['消息扩展'];
override payloadExample = {
user_id: '123456',
phone_number: ''
};
override returnExample = {
ark: '...'
};
async _handle (payload: PayloadType) {
if (payload.group_id) {
return await this.core.apis.GroupApi.getGroupRecommendContactArkJson(payload.group_id.toString());
} else if (payload.user_id) {
@@ -28,18 +39,30 @@ export class SharePeerBase extends OneBotAction<Payload, GeneralCallResult & {
}
}
const SchemaDataGroupEx = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchemaGroupEx = Type.Object({
group_id: Type.String({ description: '群号' }),
});
export class SharePeer extends SharePeerBase {
override actionName = ActionName.SharePeer;
}
type PayloadGroupEx = Static<typeof SchemaDataGroupEx>;
type PayloadTypeGroupEx = Static<typeof PayloadSchemaGroupEx>;
export class ShareGroupExBase extends OneBotAction<PayloadGroupEx, string> {
override payloadSchema = SchemaDataGroupEx;
const ReturnSchemaGroupEx = Type.String({ description: 'Ark Json内容' });
async _handle (payload: PayloadGroupEx) {
type ReturnTypeGroupEx = Static<typeof ReturnSchemaGroupEx>;
export class ShareGroupExBase extends OneBotAction<PayloadTypeGroupEx, ReturnTypeGroupEx> {
override payloadSchema = PayloadSchemaGroupEx;
override returnSchema = ReturnSchemaGroupEx;
override actionSummary = '分享群 (Ark)';
override actionDescription = '获取群分享的 Ark 内容';
override actionTags = ['消息扩展'];
override payloadExample = {
group_id: '123456'
};
override returnExample = '{"app": "com.tencent.structmsg", ...}';
async _handle (payload: PayloadTypeGroupEx) {
return await this.core.apis.GroupApi.getArkJsonGroupShare(payload.group_id.toString());
}
}
@@ -3,22 +3,34 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface TransGroupFileResponse {
ok: boolean;
}
const ReturnSchema = Type.Object({
ok: Type.Boolean({ description: '是否成功' }),
}, { description: '转发文件结果' });
export class TransGroupFile extends GetPacketStatusDepends<Payload, TransGroupFileResponse> {
type ReturnType = Static<typeof ReturnSchema>;
export class TransGroupFile extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.TransGroupFile;
override payloadSchema = SchemaData;
override actionSummary = '传输群文件';
override actionTags = ['文件扩展'];
override payloadExample = {
group_id: '123456',
file_id: '/file_id'
};
override returnExample = {
ok: true
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
const result = await this.core.apis.GroupApi.transGroupFile(payload.group_id.toString(), contextMsgFile.fileUUID);
@@ -2,21 +2,37 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
words: Type.Array(Type.String()),
import { ExtendsActionsExamples } from '../example/ExtendsActionsExamples';
const PayloadSchema = Type.Object({
words: Type.Array(Type.String(), { description: '待翻译单词列表' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class TranslateEnWordToZn extends OneBotAction<Payload, Array<unknown> | null> {
const ReturnSchema = Type.Object({
words: Type.Array(Type.String(), { description: '翻译结果列表' }),
}, { description: '翻译结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class TranslateEnWordToZn extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.TranslateEnWordToZn;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '英文单词翻译';
override actionDescription = '将英文单词列表翻译为中文';
override actionTags = ['扩展接口'];
override payloadExample = ExtendsActionsExamples.TranslateEnWordToZn.payload;
override returnExample = ExtendsActionsExamples.TranslateEnWordToZn.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType): Promise<ReturnType> {
const ret = await this.core.apis.SystemApi.translateEnWordToZn(payload.words);
if (ret.result !== 0) {
throw new Error('翻译失败');
}
return ret.words;
return {
words: ret.words
};
}
}
@@ -5,20 +5,36 @@ import { Static, Type } from '@sinclair/typebox';
import { existsSync } from 'node:fs';
import { unlink } from 'node:fs/promises';
const SchemaData = Type.Object({
group_id: Type.String(),
album_id: Type.String(),
album_name: Type.String(),
file: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
album_id: Type.String({ description: '相册ID' }),
album_name: Type.String({ description: '相册名称' }),
file: Type.String({ description: '图片路径、URL或Base64' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class UploadImageToQunAlbum extends OneBotAction<Payload, unknown> {
const ReturnSchema = Type.Any({ description: '上传结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class UploadImageToQunAlbum extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.UploadImageToQunAlbum;
override payloadSchema = SchemaData;
override actionSummary = '上传图片到群相册';
override actionTags = ['群组扩展'];
override payloadExample = {
group_id: '123456',
album_id: 'album_id_1',
album_name: '相册1',
file: '/path/to/image.jpg'
};
override returnExample = {
result: null
};
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, payload.file);
try {
return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path);
+25 -14
View File
@@ -5,23 +5,29 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { OB11MessageImage, OB11MessageVideo } from '@/napcat-onebot/types';
import { Static, Type } from '@sinclair/typebox';
export interface GetFileResponse {
file?: string; // path
url?: string;
file_size?: string;
file_name?: string;
base64?: string;
}
import { FileActionsExamples } from '../example/FileActionsExamples';
const GetFileBase_PayloadSchema = Type.Object({
file: Type.Optional(Type.String()),
file_id: Type.Optional(Type.String()),
export const GetFilePayloadSchema = Type.Object({
file: Type.Optional(Type.String({ description: '文件路径、URL或Base64' })),
file_id: Type.Optional(Type.String({ description: '文件ID' })),
});
export type GetFilePayload = Static<typeof GetFileBase_PayloadSchema>;
export type GetFilePayload = Static<typeof GetFilePayloadSchema>;
export const GetFileReturnSchema = Type.Object({
file: Type.Optional(Type.String({ description: '本地路径' })),
url: Type.Optional(Type.String({ description: '下载URL' })),
file_size: Type.Optional(Type.String({ description: '文件大小' })),
file_name: Type.Optional(Type.String({ description: '文件名' })),
base64: Type.Optional(Type.String({ description: 'Base64编码' })),
}, { description: '文件信息' });
export type GetFileResponse = Static<typeof GetFileReturnSchema>;
export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
override payloadSchema = GetFileBase_PayloadSchema;
override payloadSchema = GetFilePayloadSchema;
override returnSchema = GetFileReturnSchema;
override actionTags = ['文件接口'];
async _handle (payload: GetFilePayload): Promise<GetFileResponse> {
payload.file ||= payload.file_id || '';
@@ -40,12 +46,12 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
let url = '';
if (mixElement?.picElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageImage | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.picElement?.(mixElement?.picElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageImage | undefined;
url = tempData?.data.url ?? '';
}
if (mixElement?.videoElement && rawMessage) {
const tempData =
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageVideo | undefined;
await this.obContext.apis.MsgApi.rawToOb11Converters.videoElement?.(mixElement?.videoElement, rawMessage, mixElement, { parseMultMsg: false, disableGetUrl: false, quick_reply: true }) as OB11MessageVideo | undefined;
url = tempData?.data.url ?? '';
}
const res: GetFileResponse = {
@@ -113,4 +119,9 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
export default class GetFile extends GetFileBase {
override actionName = ActionName.GetFile;
override actionSummary = '获取文件';
override actionDescription = '获取指定文件的详细信息及下载路径';
override actionTags = ['文件接口'];
override payloadExample = FileActionsExamples.GetFile.payload;
override returnExample = FileActionsExamples.GetFile.response;
}
@@ -3,22 +3,32 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
import { FileActionsExamples } from '../example/FileActionsExamples';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface GetGroupFileUrlResponse {
url?: string;
}
const ReturnSchema = Type.Object({
url: Type.Optional(Type.String({ description: '文件下载链接' })),
}, { description: '群文件URL信息' });
export class GetGroupFileUrl extends GetPacketStatusDepends<Payload, GetGroupFileUrlResponse> {
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupFileUrl extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.GOCQHTTP_GetGroupFileUrl;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群文件URL';
override actionDescription = '获取指定群文件的下载链接';
override actionTags = ['文件接口'];
override payloadExample = FileActionsExamples.GetGroupFileUrl.payload;
override returnExample = FileActionsExamples.GetGroupFileUrl.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id) || FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (contextMsgFile?.fileUUID) {
return {
@@ -1,6 +1,13 @@
import { GetFileBase } from './GetFile';
import { ActionName } from '@/napcat-onebot/action/router';
import { FileActionsExamples } from '../example/FileActionsExamples';
export default class GetImage extends GetFileBase {
override actionName = ActionName.GetImage;
override actionSummary = '获取图片';
override actionDescription = '获取指定图片的信息及路径';
override actionTags = ['文件接口'];
override payloadExample = FileActionsExamples.GetImage.payload;
override returnExample = FileActionsExamples.GetImage.response;
}
@@ -3,21 +3,31 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
file_id: Type.String(),
import { FileActionsExamples } from '../example/FileActionsExamples';
const PayloadSchema = Type.Object({
file_id: Type.String({ description: '文件ID' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface GetPrivateFileUrlResponse {
url?: string;
}
const ReturnSchema = Type.Object({
url: Type.Optional(Type.String({ description: '文件下载链接' })),
}, { description: '私聊文件URL信息' });
export class GetPrivateFileUrl extends GetPacketStatusDepends<Payload, GetPrivateFileUrlResponse> {
type ReturnType = Static<typeof ReturnSchema>;
export class GetPrivateFileUrl extends GetPacketStatusDepends<PayloadType, ReturnType> {
override actionName = ActionName.NapCat_GetPrivateFileUrl;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取私聊文件URL';
override actionDescription = '获取指定私聊文件的下载链接';
override actionTags = ['文件接口'];
override payloadExample = FileActionsExamples.GetPrivateFileUrl.payload;
override returnExample = FileActionsExamples.GetPrivateFileUrl.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const contextMsgFile = FileNapCatOneBotUUID.decode(payload.file_id);
if (contextMsgFile?.fileUUID && contextMsgFile.msgId) {
@@ -2,22 +2,35 @@ import { GetFileBase, GetFilePayload, GetFileResponse } from './GetFile';
import { ActionName } from '@/napcat-onebot/action/router';
import { promises as fs } from 'fs';
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
import { Static, Type } from '@sinclair/typebox';
const out_format = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'];
import { FileActionsExamples } from '../example/FileActionsExamples';
type Payload = {
out_format: string;
} & GetFilePayload;
const out_format_list = ['mp3', 'amr', 'wma', 'm4a', 'spx', 'ogg', 'wav', 'flac'];
const PayloadSchema = Type.Object({
file: Type.Optional(Type.String({ description: '文件路径、URL或Base64' })),
file_id: Type.Optional(Type.String({ description: '文件ID' })),
out_format: Type.String({ description: '输出格式' }),
});
type PayloadType = Static<typeof PayloadSchema>;
export default class GetRecord extends GetFileBase {
override actionName = ActionName.GetRecord;
override payloadSchema = PayloadSchema;
override actionSummary = '获取语音';
override actionDescription = '获取指定语音文件的信息,并支持格式转换';
override actionTags = ['文件接口'];
override payloadExample = FileActionsExamples.GetRecord.payload;
override returnExample = FileActionsExamples.GetRecord.response;
override async _handle (payload: Payload): Promise<GetFileResponse> {
const res = await super._handle(payload);
override async _handle (payload: PayloadType): Promise<GetFileResponse> {
const res = await super._handle(payload as GetFilePayload);
if (payload.out_format && typeof payload.out_format === 'string') {
const inputFile = res.file;
if (!inputFile) throw new Error('file not found');
if (!out_format.includes(payload.out_format)) {
if (!out_format_list.includes(payload.out_format)) {
throw new Error('转换失败 out_format 字段可能格式不正确');
}
const outputFile = `${inputFile}.${payload.out_format}`;
@@ -1,24 +1,71 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import path from 'node:path';
// 不全部使用json因为:一个文件解析Form-data会变字符串!!! 但是api文档就写List
const SchemaData = Type.Object({
const richMediaList = [
'.mp4', '.mov', '.avi', '.wmv', '.mpeg', '.mpg', '.flv', '.mkv',
'.png', '.gif', '.jpg', '.jpeg', '.webp', '.bmp',
];
export const CreateFlashTaskPayloadSchema = Type.Object({
files: Type.Union([
Type.Array(Type.String()),
Type.String(),
]),
], { description: '文件列表或单个文件路径' }),
name: Type.Optional(Type.String({ description: '任务名称' })),
thumb_path: Type.Optional(Type.String({ description: '缩略图路径' })),
});
type Payload = Static<typeof SchemaData>;
export type CreateFlashTaskPayload = Static<typeof CreateFlashTaskPayloadSchema>;
export class CreateFlashTask extends OneBotAction<Payload, unknown> {
export class CreateFlashTask extends OneBotAction<CreateFlashTaskPayload, any> {
override actionName = ActionName.CreateFlashTask;
override payloadSchema = SchemaData;
override payloadSchema = CreateFlashTaskPayloadSchema;
override returnSchema = Type.Any({ description: '任务创建结果' });
override actionSummary = '创建闪传任务';
override actionTags = ['文件扩展'];
override payloadExample = {
files: 'C:\\test.jpg',
name: 'test_task'
};
override returnExample = {
task_id: 'task_123'
};
async _handle (payload: Payload) {
// todo fileset的名字和缩略图还没实现!!
async _handle (payload: CreateFlashTaskPayload) {
const fileList = Array.isArray(payload.files) ? payload.files : [payload.files];
let thumbPath: string = '';
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList);
if (fileList.length === 1) {
// 我是真没hook到那种合并的缩略图是哪个方法产生的,暂时不实现(怀疑是js直接canvas渲染的!!) // 确认了猜想
const filePath = fileList[0];
if (filePath === undefined) {
return {};
}
const ext = path.extname(filePath).toLowerCase();
if (richMediaList.includes(ext)) {
try {
const res = await this.core.apis.FlashApi.createFileThumbnail(filePath);
if (res && typeof res === 'object' && 'result' in res && res.result === 0) {
thumbPath = res.targetPath as string;
}
} catch (_e) {
}
}
}
function toPlatformPath (inputPath: string) {
const unifiedPath = inputPath.replace(/[\\/]/g, path.sep);
return path.normalize(unifiedPath);
}
let normalPath: string;
if (payload.thumb_path !== undefined) {
normalPath = path.normalize(payload.thumb_path);
} else {
normalPath = toPlatformPath(thumbPath);
}
return await this.core.apis.FlashApi.createFlashTransferUploadTask(fileList, normalPath, payload.name || '');
}
}
@@ -2,17 +2,24 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
fileset_id: Type.String(),
export const DownloadFilesetPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type DownloadFilesetPayload = Static<typeof DownloadFilesetPayloadSchema>;
export class DownloadFileset extends OneBotAction<Payload, unknown> {
export class DownloadFileset extends OneBotAction<DownloadFilesetPayload, any> {
override actionName = ActionName.DownloadFileset;
override payloadSchema = SchemaData;
override payloadSchema = DownloadFilesetPayloadSchema;
override returnSchema = Type.Any({ description: '下载结果' });
override actionSummary = '下载文件集';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: DownloadFilesetPayload) {
// 默认路径 / fileset_id /为下载路径
return await this.core.apis.FlashApi.downloadFileSetBySetId(payload.fileset_id);
}
@@ -2,19 +2,31 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
share_code: Type.String(),
export const GetFilesetIdPayloadSchema = Type.Object({
share_code: Type.String({ description: '分享码或分享链接' }),
});
type Payload = Static<typeof SchemaData>;
export type GetFilesetIdPayload = Static<typeof GetFilesetIdPayloadSchema>;
export class GetFilesetId extends OneBotAction<Payload, unknown> {
export class GetFilesetId extends OneBotAction<GetFilesetIdPayload, { fileset_id: string }> {
override actionName = ActionName.GetFilesetId;
override payloadSchema = SchemaData;
override payloadSchema = GetFilesetIdPayloadSchema;
override returnSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' })
});
override actionSummary = '获取文件集 ID';
override actionTags = ['文件扩展'];
override payloadExample = {
share_code: '123456'
};
override returnExample = {
fileset_id: 'set_123'
};
async _handle (payload: Payload) {
async _handle (payload: GetFilesetIdPayload) {
// 适配share_link 防止被传 Link无法解析
const code = payload.share_code.includes('=') ? payload.share_code.split('=').slice(1).join('=') : payload.share_code;
return await this.core.apis.FlashApi.fromShareLinkFindSetId(code);
const result = await this.core.apis.FlashApi.fromShareLinkFindSetId(code);
return { fileset_id: result.fileSetId };
}
}
@@ -2,17 +2,27 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
fileset_id: Type.String(),
export const GetFilesetInfoPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type GetFilesetInfoPayload = Static<typeof GetFilesetInfoPayloadSchema>;
export class GetFilesetInfo extends OneBotAction<Payload, unknown> {
export class GetFilesetInfo extends OneBotAction<GetFilesetInfoPayload, any> {
override actionName = ActionName.GetFilesetInfo;
override payloadSchema = SchemaData;
override payloadSchema = GetFilesetInfoPayloadSchema;
override returnSchema = Type.Any({ description: '文件集信息' });
override actionSummary = '获取文件集信息';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
};
override returnExample = {
fileset_id: 'set_123',
file_list: []
};
async _handle (payload: Payload) {
async _handle (payload: GetFilesetInfoPayload) {
return await this.core.apis.FlashApi.getFileSetIndoBySetId(payload.fileset_id);
}
}
@@ -2,17 +2,29 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
fileset_id: Type.String(),
export const GetFlashFileListPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type GetFlashFileListPayload = Static<typeof GetFlashFileListPayloadSchema>;
export class GetFlashFileList extends OneBotAction<Payload, unknown> {
export class GetFlashFileList extends OneBotAction<GetFlashFileListPayload, any> {
override actionName = ActionName.GetFlashFileList;
override payloadSchema = SchemaData;
override payloadSchema = GetFlashFileListPayloadSchema;
override returnSchema = Type.Any({ description: '文件列表' });
override actionSummary = '获取闪传文件列表';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
};
override returnExample = [
{
file_name: 'test.jpg',
size: 1024
}
];
async _handle (payload: Payload) {
async _handle (payload: GetFlashFileListPayload) {
return await this.core.apis.FlashApi.getFileListBySetId(payload.fileset_id);
}
}
@@ -2,19 +2,28 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
fileset_id: Type.String(),
file_name: Type.Optional(Type.String()),
file_index: Type.Optional(Type.Number()),
export const GetFlashFileUrlPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
file_name: Type.Optional(Type.String({ description: '文件名' })),
file_index: Type.Optional(Type.Number({ description: '文件索引' })),
});
type Payload = Static<typeof SchemaData>;
export type GetFlashFileUrlPayload = Static<typeof GetFlashFileUrlPayloadSchema>;
export class GetFlashFileUrl extends OneBotAction<Payload, unknown> {
export class GetFlashFileUrl extends OneBotAction<GetFlashFileUrlPayload, any> {
override actionName = ActionName.GetFlashFileUrl;
override payloadSchema = SchemaData;
override payloadSchema = GetFlashFileUrlPayloadSchema;
override returnSchema = Type.Any({ description: '文件下载链接' });
override actionSummary = '获取闪传文件链接';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
};
override returnExample = {
url: 'http://example.com/flash.jpg'
};
async _handle (payload: Payload) {
async _handle (payload: GetFlashFileUrlPayload) {
// 文件的索引依旧从0开始
return await this.core.apis.FlashApi.getFileTransUrl(payload.fileset_id, {
fileName: payload.file_name,
@@ -2,17 +2,24 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
fileset_id: Type.String(),
export const GetShareLinkPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type GetShareLinkPayload = Static<typeof GetShareLinkPayloadSchema>;
export class GetShareLink extends OneBotAction<Payload, unknown> {
export class GetShareLink extends OneBotAction<GetShareLinkPayload, any> {
override actionName = ActionName.GetShareLink;
override payloadSchema = SchemaData;
override payloadSchema = GetShareLinkPayloadSchema;
override returnSchema = Type.Any({ description: '分享链接' });
override actionSummary = '获取文件分享链接';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123'
};
override returnExample = 'http://example.com/share';
async _handle (payload: Payload) {
async _handle (payload: GetShareLinkPayload) {
return await this.core.apis.FlashApi.getShareLinkBySetId(payload.fileset_id);
}
}
@@ -3,19 +3,29 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType, Peer } from 'napcat-core/types';
const SchemaData = Type.Object({
fileset_id: Type.String(),
user_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
group_id: Type.Optional(Type.Union([Type.Number(), Type.String()])),
export const SendFlashMsgPayloadSchema = Type.Object({
fileset_id: Type.String({ description: '文件集 ID' }),
user_id: Type.Optional(Type.String({ description: '用户 QQ' })),
group_id: Type.Optional(Type.String({ description: '群号' })),
});
type Payload = Static<typeof SchemaData>;
export type SendFlashMsgPayload = Static<typeof SendFlashMsgPayloadSchema>;
export class SendFlashMsg extends OneBotAction<Payload, unknown> {
export class SendFlashMsg extends OneBotAction<SendFlashMsgPayload, any> {
override actionName = ActionName.SendFlashMsg;
override payloadSchema = SchemaData;
override payloadSchema = SendFlashMsgPayloadSchema;
override returnSchema = Type.Any({ description: '发送结果' });
override actionSummary = '发送闪传消息';
override actionTags = ['文件扩展'];
override payloadExample = {
fileset_id: 'set_123',
user_id: '123456789'
};
override returnExample = {
message_id: 123456
};
async _handle (payload: Payload) {
async _handle (payload: SendFlashMsgPayload) {
let peer: Peer;
if (payload.group_id) {
@@ -3,18 +3,26 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
msg_id: Type.String(),
export const CancelOnlineFilePayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
msg_id: Type.String({ description: '消息 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type CancelOnlineFilePayload = Static<typeof CancelOnlineFilePayloadSchema>;
export class CancelOnlineFile extends OneBotAction<Payload, unknown> {
export class CancelOnlineFile extends OneBotAction<CancelOnlineFilePayload, any> {
override actionName = ActionName.CancelOnlineFile;
override payloadSchema = SchemaData;
override payloadSchema = CancelOnlineFilePayloadSchema;
override returnSchema = Type.Any({ description: '取消结果' });
override actionSummary = '取消在线文件';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
msg_id: '123'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: CancelOnlineFilePayload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -3,17 +3,24 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
export const GetOnlineFileMessagesPayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
});
type Payload = Static<typeof SchemaData>;
export type GetOnlineFileMessagesPayload = Static<typeof GetOnlineFileMessagesPayloadSchema>;
export class GetOnlineFileMessages extends OneBotAction<Payload, unknown> {
export class GetOnlineFileMessages extends OneBotAction<GetOnlineFileMessagesPayload, any> {
override actionName = ActionName.GetOnlineFileMessages;
override payloadSchema = SchemaData;
override payloadSchema = GetOnlineFileMessagesPayloadSchema;
override returnSchema = Type.Any({ description: '在线文件消息列表' });
override actionSummary = '获取在线文件消息';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789'
};
override returnExample = [];
async _handle (payload: Payload) {
async _handle (payload: GetOnlineFileMessagesPayload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -3,19 +3,28 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
msg_id: Type.String(),
element_id: Type.String(),
export const ReceiveOnlineFilePayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
msg_id: Type.String({ description: '消息 ID' }),
element_id: Type.String({ description: '元素 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type ReceiveOnlineFilePayload = Static<typeof ReceiveOnlineFilePayloadSchema>;
export class ReceiveOnlineFile extends OneBotAction<Payload, unknown> {
export class ReceiveOnlineFile extends OneBotAction<ReceiveOnlineFilePayload, any> {
override actionName = ActionName.ReceiveOnlineFile;
override payloadSchema = SchemaData;
override payloadSchema = ReceiveOnlineFilePayloadSchema;
override returnSchema = Type.Any({ description: '接收结果' });
override actionSummary = '接收在线文件';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
msg_id: '123',
save_path: 'C:\\save'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: ReceiveOnlineFilePayload) {
// 默认下载路径
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -3,19 +3,27 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
msg_id: Type.String(),
element_id: Type.String(),
export const RefuseOnlineFilePayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
msg_id: Type.String({ description: '消息 ID' }),
element_id: Type.String({ description: '元素 ID' }),
});
type Payload = Static<typeof SchemaData>;
export type RefuseOnlineFilePayload = Static<typeof RefuseOnlineFilePayloadSchema>;
export class RefuseOnlineFile extends OneBotAction<Payload, unknown> {
export class RefuseOnlineFile extends OneBotAction<RefuseOnlineFilePayload, any> {
override actionName = ActionName.RefuseOnlineFile;
override payloadSchema = SchemaData;
override payloadSchema = RefuseOnlineFilePayloadSchema;
override returnSchema = Type.Any({ description: '拒绝结果' });
override actionSummary = '拒绝在线文件';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
msg_id: '123'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: RefuseOnlineFilePayload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -3,19 +3,28 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
file_path: Type.String(),
file_name: Type.Optional(Type.String()),
export const SendOnlineFilePayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
file_path: Type.String({ description: '本地文件路径' }),
file_name: Type.Optional(Type.String({ description: '文件名 (可选)' })),
});
type Payload = Static<typeof SchemaData>;
export type SendOnlineFilePayload = Static<typeof SendOnlineFilePayloadSchema>;
export class SendOnlineFile extends OneBotAction<Payload, unknown> {
export class SendOnlineFile extends OneBotAction<SendOnlineFilePayload, any> {
override actionName = ActionName.SendOnlineFile;
override payloadSchema = SchemaData;
override payloadSchema = SendOnlineFilePayloadSchema;
override returnSchema = Type.Any({ description: '发送结果' });
override actionSummary = '发送在线文件';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
file_path: 'C:\\path\\to\\file.txt',
file_name: 'test.txt'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: SendOnlineFilePayload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -3,19 +3,27 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { ChatType } from 'napcat-core/types';
const SchemaData = Type.Object({
user_id: Type.Union([Type.Number(), Type.String()]),
folder_path: Type.String(),
folder_name: Type.Optional(Type.String()),
export const SendOnlineFolderPayloadSchema = Type.Object({
user_id: Type.String({ description: '用户 QQ' }),
folder_path: Type.String({ description: '本地文件夹路径' }),
folder_name: Type.Optional(Type.String({ description: '文件夹名称 (可选)' })),
});
type Payload = Static<typeof SchemaData>;
export type SendOnlineFolderPayload = Static<typeof SendOnlineFolderPayloadSchema>;
export class SendOnlineFolder extends OneBotAction<Payload, unknown> {
export class SendOnlineFolder extends OneBotAction<SendOnlineFolderPayload, any> {
override actionName = ActionName.SendOnlineFolder;
override payloadSchema = SchemaData;
override payloadSchema = SendOnlineFolderPayloadSchema;
override returnSchema = Type.Any({ description: '发送结果' });
override actionSummary = '发送在线文件夹';
override actionTags = ['文件扩展'];
override payloadExample = {
user_id: '123456789',
folder_path: 'C:\\path\\to\\folder'
};
override returnExample = null;
async _handle (payload: Payload) {
async _handle (payload: SendOnlineFolderPayload) {
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('User not found');
@@ -2,23 +2,40 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
// 兼容gocq 与name二选一
folder_name: Type.Optional(Type.String()),
folder_name: Type.Optional(Type.String({ description: '文件夹名称' })),
// 兼容gocq 与folder_name二选一
name: Type.Optional(Type.String()),
name: Type.Optional(Type.String({ description: '文件夹名称' })),
});
type Payload = Static<typeof SchemaData>;
interface ResponseType {
result: unknown;
groupItem: unknown;
}
export class CreateGroupFileFolder extends OneBotAction<Payload, ResponseType> {
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
result: Type.Any({ description: '操作结果' }),
groupItem: Type.Any({ description: '群项信息' }),
}, { description: '创建文件夹结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class CreateGroupFileFolder extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_CreateGroupFileFolder;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '创建群文件目录';
override actionDescription = '在群文件系统中创建新的文件夹';
override actionTags = ['Go-CQHTTP'];
override payloadExample = {
group_id: '123456789',
folder_name: '新建文件夹'
};
override returnExample = {
result: {},
groupItem: {}
};
async _handle (payload: PayloadType) {
const folderName = payload.folder_name || payload.name;
return (await this.core.apis.GroupApi.creatGroupFileFolder(payload.group_id.toString(), folderName!)).resultWithGroupItem;
}
@@ -2,19 +2,30 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
import { Static, Type } from '@sinclair/typebox';
import { NTQQGroupApi } from 'napcat-core/apis';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_id: Type.String(),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_id: Type.String({ description: '文件ID' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class DeleteGroupFile extends OneBotAction<Payload, Awaited<ReturnType<NTQQGroupApi['delGroupFile']>>> {
const ReturnSchema = Type.Any({ description: '删除结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class DeleteGroupFile extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GOCQHTTP_DeleteGroupFile;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '删除群文件';
override actionDescription = '在群文件系统中删除指定的文件';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.DeleteGroupFile.payload;
override returnExample = GoCQHTTPActionsExamples.DeleteGroupFile.response;
async _handle (payload: PayloadType) {
const data = FileNapCatOneBotUUID.decodeModelId(payload.file_id);
if (!data || !data.fileId) throw new Error('Invalid file_id');
return await this.core.apis.GroupApi.delGroupFile(payload.group_id.toString(), [data.fileId]);
@@ -1,20 +1,31 @@
import { ActionName } from '@/napcat-onebot/action/router';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { Static, Type } from '@sinclair/typebox';
import { NTQQGroupApi } from 'napcat-core/apis';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
folder_id: Type.Optional(Type.String()),
folder: Type.Optional(Type.String()),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
folder_id: Type.Optional(Type.String({ description: '文件夹ID' })),
folder: Type.Optional(Type.String({ description: '文件夹ID' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class DeleteGroupFileFolder extends OneBotAction<Payload, Awaited<ReturnType<NTQQGroupApi['delGroupFileFolder']>>['groupFileCommonResult']> {
const ReturnSchema = Type.Any({ description: '删除结果' });
type ReturnType = Static<typeof ReturnSchema>;
export class DeleteGroupFileFolder extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_DeleteGroupFileFolder;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '删除群文件目录';
override actionDescription = '在群文件系统中删除指定的文件夹';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.DeleteGroupFileFolder.payload;
override returnExample = GoCQHTTPActionsExamples.DeleteGroupFileFolder.response;
async _handle (payload: PayloadType) {
return (await this.core.apis.GroupApi.delGroupFileFolder(
payload.group_id.toString(), payload.folder ?? payload.folder_id ?? '')).groupFileCommonResult;
}
@@ -5,28 +5,37 @@ import { join as joinPath } from 'node:path';
import { calculateFileMD5, uriToLocalFile } from 'napcat-common/src/file';
import { randomUUID } from 'crypto';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
interface FileResponse {
file: string;
}
const SchemaData = Type.Object({
url: Type.Optional(Type.String()),
base64: Type.Optional(Type.String()),
name: Type.Optional(Type.String()),
headers: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
const PayloadSchema = Type.Object({
url: Type.Optional(Type.String({ description: '下载链接' })),
base64: Type.Optional(Type.String({ description: 'base64数据' })),
name: Type.Optional(Type.String({ description: '文件名' })),
headers: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())], { description: '请求头' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class GoCQHTTPDownloadFile extends OneBotAction<Payload, FileResponse> {
const ReturnSchema = Type.Object({
file: Type.String({ description: '文件路径' }),
}, { description: '下载结果' });
type ReturnType = Static<typeof ReturnSchema>;
export default class GoCQHTTPDownloadFile extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_DownloadFile;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '下载文件';
override actionDescription = '下载网络文件到本地临时目录';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.DownloadFile.payload;
override returnExample = GoCQHTTPActionsExamples.DownloadFile.response;
async _handle (payload: Payload): Promise<FileResponse> {
async _handle (payload: PayloadType): Promise<ReturnType> {
const isRandomName = !payload.name;
const name = payload.name || randomUUID();
let result: Awaited<ReturnType<typeof uriToLocalFile>>;
let result: Awaited<globalThis.ReturnType<typeof uriToLocalFile>>;
if (payload.base64) {
result = await uriToLocalFile(this.core.NapCatTempPath, `base64://${payload.base64}`, name);
@@ -5,18 +5,34 @@ import { MessageUnique } from 'napcat-common/src/message-unique';
import { Static, Type } from '@sinclair/typebox';
import { ChatType, ElementType, MsgSourceType, NTMsgType, RawMessage } from 'napcat-core';
import { isNumeric } from 'napcat-common/src/helper';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
message_id: Type.Optional(Type.String()),
id: Type.Optional(Type.String()),
const PayloadSchema = Type.Object({
message_id: Type.Optional(Type.String({ description: '消息ID' })),
id: Type.Optional(Type.String({ description: '消息ID' })),
});
type Payload = Static<typeof SchemaData>;
export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
messages: OB11Message[] | undefined;
}> {
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
messages: Type.Optional(Type.Array(Type.Unknown(), { description: '消息列表' })),
}, { description: '合并转发消息' });
type ReturnType = Static<typeof ReturnSchema>;
function isForward (msg: OB11MessageData | string): msg is OB11MessageForward {
return typeof msg !== 'string' && msg.type === OB11MessageDataType.forward;
}
export class GoCQHTTPGetForwardMsgAction extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetForwardMsg;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取合并转发消息';
override actionDescription = '获取合并转发消息的具体内容';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetForwardMsg.payload;
override returnExample = GoCQHTTPActionsExamples.GetForwardMsg.response;
private createTemplateNode (message: OB11Message): OB11MessageNode {
return {
@@ -37,13 +53,18 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
const templateNode = this.createTemplateNode(message);
for (const msgdata of message.message) {
if ((msgdata as OB11MessageData).type === OB11MessageDataType.forward) {
if (isForward(msgdata)) {
const newNode = this.createTemplateNode(message);
newNode.data.message = await this.parseForward((msgdata as OB11MessageForward).data.content ?? []);
newNode.data.message = await this.parseForward(msgdata.data.content ?? []);
templateNode.data.message.push(newNode);
} else {
templateNode.data.message.push(msgdata as OB11MessageData);
if (typeof msgdata === 'string') {
const textMsg: OB11MessageData = { type: OB11MessageDataType.text, data: { text: msgdata } };
templateNode.data.message.push(textMsg);
} else {
templateNode.data.message.push(msgdata);
}
}
}
retMsg.push(templateNode);
@@ -52,7 +73,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
return retMsg;
}
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
// 1. 检查消息ID是否存在
const msgId = payload.message_id || payload.id;
if (!msgId) {
@@ -61,7 +82,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
// 2. 定义辅助函数 - 创建伪转发消息对象
const createFakeForwardMsg = (resId: string): RawMessage => {
return {
const fakeMsg: RawMessage = {
chatType: ChatType.KCHATTYPEGROUP,
elements: [{
elementType: ElementType.MULTIFORWARD,
@@ -74,7 +95,7 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
}],
guildId: '',
isOnlineMsg: false,
msgId: '', // TODO: no necessary
msgId: '', // TODO: no necessary
msgRandom: '0',
msgSeq: '',
msgTime: '',
@@ -95,15 +116,17 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
senderUin: '1094950020',
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
subMsgType: 1,
} as RawMessage;
};
return fakeMsg;
};
// 3. 定义协议回退逻辑函数
const protocolFallbackLogic = async (resId: string) => {
const ob = (await this.obContext.apis.MsgApi.parseMessageV2(createFakeForwardMsg(resId), true))?.arrayMsg;
if (ob) {
const firstMsg = ob?.message?.[0];
if (firstMsg && isForward(firstMsg)) {
return {
messages: (ob?.message?.[0] as OB11MessageForward)?.data?.content,
messages: firstMsg.data.content,
};
}
throw new Error('protocolFallbackLogic: 找不到相关的聊天记录');
@@ -132,9 +155,12 @@ export class GoCQHTTPGetForwardMsgAction extends OneBotAction<Payload, {
// 6. 解析消息内容
const resMsg = (await this.obContext.apis.MsgApi.parseMessage(singleMsg, 'array', true));
const forwardContent = (resMsg?.message?.[0] as OB11MessageForward)?.data?.content;
if (forwardContent) {
return { messages: forwardContent };
const firstMsg = resMsg?.message?.[0];
if (firstMsg && isForward(firstMsg)) {
const forwardContent = firstMsg.data.content;
if (forwardContent) {
return { messages: forwardContent };
}
}
}
}
@@ -6,28 +6,38 @@ import { MessageUnique } from 'napcat-common/src/message-unique';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
interface Response {
messages: OB11Message[];
}
const SchemaData = Type.Object({
user_id: Type.String(),
message_seq: Type.Optional(Type.String()),
count: Type.Number({ default: 20 }),
reverse_order: Type.Boolean({ default: false }),
disable_get_url: Type.Boolean({ default: false }),
parse_mult_msg: Type.Boolean({ default: true }),
quick_reply: Type.Boolean({ default: false }),
reverseOrder: Type.Boolean({ default: false }),// @deprecated 兼容旧版本
const PayloadSchema = Type.Object({
user_id: Type.String({ description: '用户QQ' }),
message_seq: Type.Optional(Type.String({ description: '起始消息序号' })),
count: Type.Number({ default: 20, description: '获取消息数量' }),
reverse_order: Type.Boolean({ default: false, description: '是否反向排序' }),
disable_get_url: Type.Boolean({ default: false, description: '是否禁用获取URL' }),
parse_mult_msg: Type.Boolean({ default: true, description: '是否解析合并消息' }),
quick_reply: Type.Boolean({ default: false, description: '是否快速回复' }),
reverseOrder: Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class GetFriendMsgHistory extends OneBotAction<Payload, Response> {
const ReturnSchema = Type.Object({
messages: Type.Array(Type.Any(), { description: '消息列表' }),
}, { description: '好友历史消息' });
type ReturnType = Static<typeof ReturnSchema>;
export default class GetFriendMsgHistory extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetFriendMsgHistory;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取好友历史消息';
override actionDescription = '获取指定好友的历史聊天记录';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetFriendMsgHistory.payload;
override returnExample = GoCQHTTPActionsExamples.GetFriendMsgHistory.response;
async _handle (payload: Payload, _adapter: string, config: NetworkAdapterConfig): Promise<Response> {
async _handle (payload: PayloadType, _adapter: string, config: NetworkAdapterConfig): Promise<ReturnType> {
// 处理参数
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error(`记录${payload.user_id}不存在`);
@@ -46,7 +56,7 @@ export default class GetFriendMsgHistory extends OneBotAction<Payload, Response>
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url)))
).filter(msg => msg !== undefined);
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
}
@@ -1,22 +1,33 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
});
type Payload = Static<typeof SchemaData>;
interface ResponseType {
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}
export class GoCQHTTPGetGroupAtAllRemain extends OneBotAction<Payload, ResponseType> {
override actionName = ActionName.GoCQHTTP_GetGroupAtAllRemain;
override payloadSchema = SchemaData;
type PayloadType = Static<typeof PayloadSchema>;
async _handle (payload: Payload) {
const ReturnSchema = Type.Object({
can_at_all: Type.Boolean({ description: '是否可以艾特全体' }),
remain_at_all_count_for_group: Type.Number({ description: '群艾特全体剩余次数' }),
remain_at_all_count_for_uin: Type.Number({ description: '个人艾特全体剩余次数' }),
}, { description: '群艾特全体剩余次数' });
type ReturnType = Static<typeof ReturnSchema>;
export class GoCQHTTPGetGroupAtAllRemain extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetGroupAtAllRemain;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群艾特全体剩余次数';
override actionDescription = '获取指定群聊中艾特全体成员的剩余次数';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupAtAllRemain.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupAtAllRemain.response;
async _handle (payload: PayloadType) {
const ret = await this.core.apis.GroupApi.getGroupRemainAtTimes(payload.group_id.toString());
const data = {
can_at_all: ret.atInfo.canAtAll,
@@ -1,23 +1,34 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetGroupFileSystemInfo extends OneBotAction<Payload, {
file_count: number,
limit_count: number, // unimplemented
used_space: number, // TODO:unimplemented, but can be implemented later
total_space: number, // unimplemented, 10 GB by default
}> {
const ReturnSchema = Type.Object({
file_count: Type.Number({ description: '文件总数' }),
limit_count: Type.Number({ description: '文件上限' }),
used_space: Type.Number({ description: '已使用空间' }),
total_space: Type.Number({ description: '总空间' }),
}, { description: '群文件系统信息' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupFileSystemInfo extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetGroupFileSystemInfo;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群文件系统信息';
override actionDescription = '获取群聊文件系统的空间及状态信息';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupFileSystemInfo.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType) {
const groupFileCount = (await this.core.apis.GroupApi.getGroupFileCount([payload.group_id.toString()])).groupFileCounts[0];
if (!groupFileCount) {
throw new Error('Group not found');
@@ -2,35 +2,48 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { OB11Construct } from '@/napcat-onebot/helper/data';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
folder_id: Type.Optional(Type.String()),
folder: Type.Optional(Type.String()),
file_count: Type.Union([Type.Number(), Type.String()], { default: 50 }),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
folder_id: Type.Optional(Type.String({ description: '文件夹ID' })),
folder: Type.Optional(Type.String({ description: '文件夹ID' })),
file_count: Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetGroupFilesByFolder extends OneBotAction<Payload, {
files: ReturnType<typeof OB11Construct.file>[],
folders: never[],
}> {
const ReturnSchema = Type.Object({
files: Type.Array(Type.Unknown(), { description: '文件列表' }),
folders: Type.Array(Type.Unknown(), { description: '文件夹列表' }),
}, { description: '群文件夹文件列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetGroupFilesByFolder;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
const ret = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群文件夹文件列表';
override actionDescription = '获取指定群文件夹下的文件及子文件夹列表';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupFilesByFolder.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupFilesByFolder.response;
async _handle (payload: PayloadType): Promise<ReturnType> {
const retRaw = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), {
sortType: 1,
fileCount: +payload.file_count,
startIndex: 0,
sortOrder: 2,
showOnlinedocFolder: 0,
folderId: payload.folder ?? payload.folder_id ?? '',
}).catch(() => []);
});
const ret = Array.isArray(retRaw) ? retRaw : [];
return {
files: ret.filter(item => item.fileInfo)
.map(item => OB11Construct.file(item.peerId, item.fileInfo!)),
folders: [] as [],
folders: [],
};
}
}
@@ -2,29 +2,38 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { WebHonorType } from 'napcat-core/types';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
type: Type.Optional(Type.Enum(WebHonorType)),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
type: Type.Optional(Type.Enum(WebHonorType, { description: '荣誉类型' })),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
interface HonorInfo {
group_id: number;
current_talkative: Record<string, unknown>;
talkative_list: unknown[];
performer_list: unknown[];
legend_list: unknown[];
emotion_list: unknown[];
strong_newbie_list: unknown[];
}
const ReturnSchema = Type.Object({
group_id: Type.Number({ description: '群号' }),
current_talkative: Type.Record(Type.String(), Type.Unknown(), { description: '当前龙王' }),
talkative_list: Type.Array(Type.Unknown(), { description: '龙王列表' }),
performer_list: Type.Array(Type.Unknown(), { description: '群聊之火列表' }),
legend_list: Type.Array(Type.Unknown(), { description: '群聊炽热列表' }),
emotion_list: Type.Array(Type.Unknown(), { description: '快乐源泉列表' }),
strong_newbie_list: Type.Array(Type.Unknown(), { description: '冒尖小春笋列表' }),
}, { description: '群荣誉信息' });
export class GetGroupHonorInfo extends OneBotAction<Payload, HonorInfo> {
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupHonorInfo extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GetGroupHonorInfo;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群荣誉信息';
override actionDescription = '获取指定群聊的荣誉信息,如龙王等';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupHonorInfo.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupHonorInfo.response;
async _handle (payload: Payload) {
async _handle (payload: PayloadType): Promise<ReturnType> {
if (!payload.type) {
payload.type = WebHonorType.ALL;
}
@@ -5,29 +5,38 @@ import { ChatType, Peer } from 'napcat-core/types';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { Static, Type } from '@sinclair/typebox';
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
interface Response {
messages: OB11Message[];
}
const SchemaData = Type.Object({
group_id: Type.String(),
message_seq: Type.Optional(Type.String()),
count: Type.Number({ default: 20 }),
reverse_order: Type.Boolean({ default: false }),
disable_get_url: Type.Boolean({ default: false }),
parse_mult_msg: Type.Boolean({ default: true }),
quick_reply: Type.Boolean({ default: false }),
reverseOrder: Type.Boolean({ default: false }),// @deprecated 兼容旧版本
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
message_seq: Type.Optional(Type.String({ description: '起始消息序号' })),
count: Type.Number({ default: 20, description: '获取消息数量' }),
reverse_order: Type.Boolean({ default: false, description: '是否反向排序' }),
disable_get_url: Type.Boolean({ default: false, description: '是否禁用获取URL' }),
parse_mult_msg: Type.Boolean({ default: true, description: '是否解析合并消息' }),
quick_reply: Type.Boolean({ default: false, description: '是否快速回复' }),
reverseOrder: Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<Payload, Response> {
const ReturnSchema = Type.Object({
messages: Type.Array(Type.Any(), { description: '消息列表' }),
}, { description: '群历史消息' });
type ReturnType = Static<typeof ReturnSchema>;
export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetGroupMsgHistory;
override payloadSchema = SchemaData;
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群历史消息';
override actionDescription = '获取指定群聊的历史聊天记录';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupMsgHistory.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupMsgHistory.response;
async _handle (payload: Payload, _adapter: string, config: NetworkAdapterConfig): Promise<Response> {
async _handle (payload: PayloadType, _adapter: string, config: NetworkAdapterConfig): Promise<ReturnType> {
const peer: Peer = { chatType: ChatType.KCHATTYPEGROUP, peerUid: payload.group_id.toString() };
const hasMessageSeq = !payload.message_seq ? !!payload.message_seq : !(payload.message_seq?.toString() === '' || payload.message_seq?.toString() === '0');
// 拉取消息
@@ -43,7 +52,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<Payload, Re
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
).filter(msg => msg !== undefined);
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
}
@@ -1,23 +1,34 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { OB11GroupFile, OB11GroupFileFolder } from '@/napcat-onebot/index';
import { OB11Construct } from '@/napcat-onebot/helper/data';
import { Static, Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
const SchemaData = Type.Object({
group_id: Type.Union([Type.Number(), Type.String()]),
file_count: Type.Union([Type.Number(), Type.String()], { default: 50 }),
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
file_count: Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' }),
});
type Payload = Static<typeof SchemaData>;
type PayloadType = Static<typeof PayloadSchema>;
export class GetGroupRootFiles extends OneBotAction<Payload, {
files: OB11GroupFile[],
folders: OB11GroupFileFolder[],
}> {
const ReturnSchema = Type.Object({
files: Type.Array(Type.Any(), { description: '文件列表' }),
folders: Type.Array(Type.Any(), { description: '文件夹列表' }),
}, { description: '群根目录文件列表' });
type ReturnType = Static<typeof ReturnSchema>;
export class GetGroupRootFiles extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_GetGroupRootFiles;
override payloadSchema = SchemaData;
async _handle (payload: Payload) {
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取群根目录文件列表';
override actionDescription = '获取群文件根目录下的所有文件和文件夹';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GetGroupRootFiles.payload;
override returnExample = GoCQHTTPActionsExamples.GetGroupRootFiles.response;
async _handle (payload: PayloadType) {
const ret = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), {
sortType: 1,
fileCount: +payload.file_count,
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more