From deae7fd467ced427a4ec9de83a374a720de32768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E5=A4=A9=E4=B8=80?= <120073078+faithleysath@users.noreply.github.com> Date: Thu, 12 Mar 2026 01:54:33 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=AF=B9=E9=BD=90=20OneBot=20schema=20?= =?UTF-8?q?=E4=B8=8E=E5=90=88=E5=B9=B6=E8=BD=AC=E5=8F=91=E6=B6=88=E6=81=AF?= =?UTF-8?q?=E5=A4=84=E7=90=86=E8=A1=8C=E4=B8=BA=20(#1694)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: make defaulted request fields optional * fix: align onebot schemas with runtime behavior * fix: tighten schema and unsupported action metadata * fix: reject empty forward reference ids * fix: update GoCQHTTPSendForwardMsg to handle messages correctly and adjust payload schema * fix: refactor message handling in GoCQHTTPSendForwardMsg and add test for message normalization * fix: update compatibility actions to return appropriate responses and align schemas with runtime behavior * fix: ensure payload properties are non-null with default values in action handlers * fix: update StreamStatus comments for clarity and enforce nickname as required in message schema * fix: integrate sleep function in GetOnlineClient and update tests to verify API call * fix: add production test checklist for OneBot schema alignment and message handling * fix: remove outdated production test checklist for OneBot schema alignment --- packages/napcat-core/apis/group.ts | 4 + packages/napcat-onebot/action/OneBotAction.ts | 13 +- .../action/example/GoCQHTTPActionsExamples.ts | 13 +- .../action/example/GuildActionsExamples.ts | 6 +- .../extends/ClickInlineKeyboardButton.ts | 12 +- .../action/extends/FetchCustomFace.ts | 4 +- .../action/extends/FetchEmojiLike.ts | 6 +- .../action/extends/GetAiCharacters.ts | 2 +- .../action/extends/GetCollectionList.ts | 4 +- .../action/extends/GetEmojiLikes.ts | 9 +- .../action/extends/GetProfileLike.ts | 8 +- .../action/extends/SendPacket.ts | 2 +- .../action/extends/SetDiyOnlineStatus.ts | 8 +- .../action/extends/SetGroupAlbumMediaLike.ts | 1 - .../action/extends/SetSpecialTitle.ts | 4 +- .../action/extends/ShareContact.ts | 2 +- .../action/file/online/ReceiveOnlineFile.ts | 2 +- .../action/go-cqhttp/GetFriendMsgHistory.ts | 22 +- .../action/go-cqhttp/GetGroupFilesByFolder.ts | 4 +- .../action/go-cqhttp/GetGroupMsgHistory.ts | 23 +- .../action/go-cqhttp/GetGroupRootFiles.ts | 4 +- .../action/go-cqhttp/GetOnlineClient.ts | 6 +- .../action/go-cqhttp/GetStrangerInfo.ts | 2 +- .../go-cqhttp/GoCQHTTPCheckUrlSafely.ts | 4 +- .../action/go-cqhttp/GoCQHTTPGetModelShow.ts | 7 +- .../action/go-cqhttp/GoCQHTTPSetModelShow.ts | 27 +- .../action/go-cqhttp/SendForwardMsg.ts | 65 ++- .../action/go-cqhttp/SendGroupNotice.ts | 25 +- .../action/go-cqhttp/UploadGroupFile.ts | 2 +- .../action/go-cqhttp/UploadPrivateFile.ts | 2 +- .../action/group/SendGroupMsg.ts | 6 + .../action/group/SetGroupAddRequest.ts | 7 +- .../napcat-onebot/action/group/SetGroupBan.ts | 4 +- .../action/group/SetGroupLeave.ts | 12 +- .../action/guild/GetGuildList.ts | 27 +- .../action/guild/GetGuildProfile.ts | 27 +- .../napcat-onebot/action/msg/MarkMsgAsRead.ts | 5 +- packages/napcat-onebot/action/msg/SendMsg.ts | 77 ++- .../action/msg/SendPrivateMsg.ts | 6 + .../action/new/GetDoubtFriendsAddRequest.ts | 4 +- .../action/new/SetDoubtFriendsAddRequest.ts | 6 +- .../action/stream/StreamBasic.ts | 16 +- .../action/stream/StreamTypes.ts | 13 + .../action/stream/TestStreamDownload.ts | 2 +- .../action/stream/UploadFileStream.ts | 2 +- .../action/system/GetSystemMsg.ts | 4 +- .../action/system/GetVersionInfo.ts | 7 +- .../action/user/GetRecentContact.ts | 4 +- .../napcat-onebot/action/user/SendLike.ts | 4 +- packages/napcat-onebot/types/message.ts | 27 +- packages/napcat-schema/index.ts | 35 +- packages/napcat-test/action-contract.test.ts | 464 ++++++++++++++++++ packages/napcat-test/schema.test.ts | 219 ++++++++- packages/napcat-test/vitest.config.ts | 2 + 54 files changed, 1078 insertions(+), 195 deletions(-) create mode 100644 packages/napcat-onebot/action/stream/StreamTypes.ts create mode 100644 packages/napcat-test/action-contract.test.ts diff --git a/packages/napcat-core/apis/group.ts b/packages/napcat-core/apis/group.ts index 2b3c17e95..3b6cc08d8 100644 --- a/packages/napcat-core/apis/group.ts +++ b/packages/napcat-core/apis/group.ts @@ -445,6 +445,10 @@ export class NTQQGroupApi { return this.context.session.getGroupService().quitGroup(groupCode); } + async destroyGroup (groupCode: string) { + return this.context.session.getGroupService().destroyGroup(groupCode); + } + async kickMember (groupCode: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') { return this.context.session.getGroupService().kickMember(groupCode, kickUids, refuseForever, kickReason); } diff --git a/packages/napcat-onebot/action/OneBotAction.ts b/packages/napcat-onebot/action/OneBotAction.ts index 4619da01f..a7745f400 100644 --- a/packages/napcat-onebot/action/OneBotAction.ts +++ b/packages/napcat-onebot/action/OneBotAction.ts @@ -1,11 +1,12 @@ import { ActionName, BaseCheckResult } from './router'; import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler'; import { Value } from '@sinclair/typebox/value'; -import { NapCatCore } from 'napcat-core'; -import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index'; -import { NetworkAdapterConfig } from '../config/config'; -import { TSchema } from '@sinclair/typebox'; -import { StreamPacket, StreamPacketBasic, StreamStatus } from './stream/StreamBasic'; +import type { NapCatCore } from 'napcat-core'; +import type { NapCatOneBot11Adapter } from '@/napcat-onebot/index'; +import type { OB11Return } from '@/napcat-onebot/types'; +import type { NetworkAdapterConfig } from '../config/config'; +import type { TSchema } from '@sinclair/typebox'; +import { StreamPacket, StreamPacketBasic, StreamStatus } from './stream/StreamTypes'; export const ActionExamples = { Common: { errors: [ @@ -57,6 +58,8 @@ export abstract class OneBotAction { actionTags: string[] = []; obContext: NapCatOneBot11Adapter; useStream: boolean = false; + supported: boolean = true; + unsupportedReason?: string = undefined; errorExamples: Array<{ code: number, description: string; }> = ActionExamples.Common.errors; constructor (obContext: NapCatOneBot11Adapter, core: NapCatCore) { diff --git a/packages/napcat-onebot/action/example/GoCQHTTPActionsExamples.ts b/packages/napcat-onebot/action/example/GoCQHTTPActionsExamples.ts index 32c19604d..d29315feb 100644 --- a/packages/napcat-onebot/action/example/GoCQHTTPActionsExamples.ts +++ b/packages/napcat-onebot/action/example/GoCQHTTPActionsExamples.ts @@ -56,7 +56,7 @@ export const GoCQHTTPActionsExamples = { response: { files: [], folders: [] }, }, GetOnlineClient: { - payload: { no_cache: false }, + payload: {}, response: [], }, GoCQHTTPCheckUrlSafely: { @@ -69,11 +69,16 @@ export const GoCQHTTPActionsExamples = { }, GoCQHTTPGetModelShow: { payload: { model: 'iPhone 13' }, - response: { variants: [] }, + response: [{ + variants: { + model_show: 'napcat', + need_pay: false, + }, + }], }, GoCQHTTPSetModelShow: { - payload: { model: 'iPhone 13', model_show: 'iPhone 13' }, - response: {}, + payload: {}, + response: null, }, QuickAction: { payload: { context: {}, operation: {} }, diff --git a/packages/napcat-onebot/action/example/GuildActionsExamples.ts b/packages/napcat-onebot/action/example/GuildActionsExamples.ts index 2e0a1fad4..895e414b8 100644 --- a/packages/napcat-onebot/action/example/GuildActionsExamples.ts +++ b/packages/napcat-onebot/action/example/GuildActionsExamples.ts @@ -1,10 +1,10 @@ export const GuildActionsExamples = { GetGuildList: { payload: {}, - response: [{ guild_id: '123456', guild_name: '测试频道' }], + response: null, }, GetGuildProfile: { - payload: { guild_id: '123456' }, - response: { guild_id: '123456', guild_name: '测试频道', guild_display_id: '123' }, + payload: {}, + response: null, }, }; diff --git a/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts b/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts index f25123b0d..1f9ab98ed 100644 --- a/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts +++ b/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts @@ -5,9 +5,9 @@ import { Static, Type } from '@sinclair/typebox'; 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: '消息序列号' }), + button_id: Type.Optional(Type.String({ default: '', description: '按钮ID' })), + callback_data: Type.Optional(Type.String({ default: '', description: '回调数据' })), + msg_seq: Type.Optional(Type.String({ default: '10086', description: '消息序列号' })), }); type PayloadType = Static; @@ -35,11 +35,11 @@ export class ClickInlineKeyboardButton extends OneBotAction; @@ -27,7 +27,7 @@ export class FetchCustomFace extends OneBotAction { ]; async _handle (payload: PayloadType) { - const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count); + const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count!); return ret.emojiInfoList.map(e => e.url); } } diff --git a/packages/napcat-onebot/action/extends/FetchEmojiLike.ts b/packages/napcat-onebot/action/extends/FetchEmojiLike.ts index a478150f9..ba94804e9 100644 --- a/packages/napcat-onebot/action/extends/FetchEmojiLike.ts +++ b/packages/napcat-onebot/action/extends/FetchEmojiLike.ts @@ -7,8 +7,8 @@ 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' }), + count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' })), + cookie: Type.Optional(Type.String({ default: '', description: '分页Cookie' })), }); type PayloadType = Static; @@ -64,7 +64,7 @@ export class FetchEmojiLike extends OneBotAction { const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0]; if (!msg) throw new Error('消息不存在'); const res = await this.core.apis.MsgApi.getMsgEmojiLikesList( - msgIdPeer.Peer, msg.msgSeq, payload.emojiId.toString(), payload.emojiType.toString(), payload.cookie, +payload.count + msgIdPeer.Peer, msg.msgSeq, payload.emojiId.toString(), payload.emojiType.toString(), payload.cookie!, +payload.count! ); return res; } diff --git a/packages/napcat-onebot/action/extends/GetAiCharacters.ts b/packages/napcat-onebot/action/extends/GetAiCharacters.ts index 3bdd5b135..5148f709b 100644 --- a/packages/napcat-onebot/action/extends/GetAiCharacters.ts +++ b/packages/napcat-onebot/action/extends/GetAiCharacters.ts @@ -6,7 +6,7 @@ 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: '聊天类型' }), + chat_type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '聊天类型' })), }); type PayloadType = Static; diff --git a/packages/napcat-onebot/action/extends/GetCollectionList.ts b/packages/napcat-onebot/action/extends/GetCollectionList.ts index 062e9c81e..fd48ffb40 100644 --- a/packages/napcat-onebot/action/extends/GetCollectionList.ts +++ b/packages/napcat-onebot/action/extends/GetCollectionList.ts @@ -4,7 +4,7 @@ import { Type, Static } from '@sinclair/typebox'; const PayloadSchema = Type.Object({ category: Type.String({ description: '分类ID' }), - count: Type.String({ default: '50', description: '获取数量' }), + count: Type.Optional(Type.String({ default: '50', description: '获取数量' })), }); type PayloadType = Static; @@ -77,6 +77,6 @@ export class GetCollectionList extends OneBotAction { }; async _handle (payload: PayloadType) { - return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count); + return await this.core.apis.CollectionApi.getAllCollection(+payload.category, +payload.count!); } } diff --git a/packages/napcat-onebot/action/extends/GetEmojiLikes.ts b/packages/napcat-onebot/action/extends/GetEmojiLikes.ts index 4806c2f16..73007abe2 100644 --- a/packages/napcat-onebot/action/extends/GetEmojiLikes.ts +++ b/packages/napcat-onebot/action/extends/GetEmojiLikes.ts @@ -9,7 +9,7 @@ const PayloadSchema = Type.Object({ 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代表全部' }), + count: Type.Optional(Type.Number({ default: 0, description: '数量,0代表全部' })), }); type PayloadType = Static; @@ -46,6 +46,7 @@ export class GetEmojiLikes extends OneBotAction { override returnSchema = ReturnSchema; async _handle (payload: PayloadType) { + const count = payload.count!; let peer: Peer; let msgId: string; @@ -66,7 +67,7 @@ export class GetEmojiLikes extends OneBotAction { const emojiType = payload.emoji_type ?? (payload.emoji_id.length > 3 ? '2' : '1'); const emojiLikeList: Array<{ user_id: string; nick_name: string; }> = []; let cookie = ''; - const needFetchCount = payload.count === 0 ? 200 : Math.ceil(payload.count / 15); + const needFetchCount = count === 0 ? 200 : Math.ceil(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 @@ -82,8 +83,8 @@ export class GetEmojiLikes extends OneBotAction { cookie = res.cookie; } // 切断多余部分 - if (payload.count > 0) { - emojiLikeList.splice(payload.count); + if (count > 0) { + emojiLikeList.splice(count); } return { emoji_like_list: emojiLikeList }; } diff --git a/packages/napcat-onebot/action/extends/GetProfileLike.ts b/packages/napcat-onebot/action/extends/GetProfileLike.ts index c9eba7e0d..b9cf60285 100644 --- a/packages/napcat-onebot/action/extends/GetProfileLike.ts +++ b/packages/napcat-onebot/action/extends/GetProfileLike.ts @@ -4,8 +4,8 @@ import { Type, Static } from '@sinclair/typebox'; 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: '获取数量' }), + start: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' })), + count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' })), }); type PayloadType = Static; @@ -61,10 +61,12 @@ export class GetProfileLike extends OneBotAction { }; async _handle (payload: PayloadType): Promise { + const start = payload.start!; + const count = payload.count!; 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; - const ret = await this.core.apis.UserApi.getProfileLike(userUid ?? this.core.selfInfo.uid, +payload.start, +payload.count, type); + const ret = await this.core.apis.UserApi.getProfileLike(userUid ?? this.core.selfInfo.uid, +start, +count, type); const data = ret.info.userLikeInfos[0]; if (!data) { throw new Error('get info error'); diff --git a/packages/napcat-onebot/action/extends/SendPacket.ts b/packages/napcat-onebot/action/extends/SendPacket.ts index aa7525116..4eead898c 100644 --- a/packages/napcat-onebot/action/extends/SendPacket.ts +++ b/packages/napcat-onebot/action/extends/SendPacket.ts @@ -6,7 +6,7 @@ import { Static, Type } from '@sinclair/typebox'; const PayloadSchema = Type.Object({ cmd: Type.String({ description: '命令字' }), data: Type.String({ description: '十六进制数据' }), - rsp: Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' }), + rsp: Type.Optional(Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' })), }); type PayloadType = Static; diff --git a/packages/napcat-onebot/action/extends/SetDiyOnlineStatus.ts b/packages/napcat-onebot/action/extends/SetDiyOnlineStatus.ts index fc9c36e16..6a30ccc64 100644 --- a/packages/napcat-onebot/action/extends/SetDiyOnlineStatus.ts +++ b/packages/napcat-onebot/action/extends/SetDiyOnlineStatus.ts @@ -4,8 +4,8 @@ import { Static, Type } from '@sinclair/typebox'; 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: '状态文字内容' }), + face_type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' })), + wording: Type.Optional(Type.String({ default: ' ', description: '状态文字内容' })), }); type PayloadType = Static; @@ -30,8 +30,8 @@ export class SetDiyOnlineStatus extends OneBotAction { async _handle (payload: PayloadType) { const ret = await this.core.apis.UserApi.setDiySelfOnlineStatus( payload.face_id.toString(), - payload.wording, - payload.face_type.toString() + payload.wording!, + payload.face_type!.toString() ); if (ret.result !== 0) { throw new Error('设置在线状态失败'); diff --git a/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts b/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts index 3e055bea3..02ae20b60 100644 --- a/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts +++ b/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts @@ -7,7 +7,6 @@ const PayloadSchema = Type.Object({ 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 PayloadType = Static; diff --git a/packages/napcat-onebot/action/extends/SetSpecialTitle.ts b/packages/napcat-onebot/action/extends/SetSpecialTitle.ts index f5b9783a0..bb34e2b3e 100644 --- a/packages/napcat-onebot/action/extends/SetSpecialTitle.ts +++ b/packages/napcat-onebot/action/extends/SetSpecialTitle.ts @@ -7,7 +7,7 @@ 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: '专属头衔' }), + special_title: Type.Optional(Type.String({ default: '', description: '专属头衔' })), }); type PayloadType = Static; @@ -29,6 +29,6 @@ export class SetSpecialTitle extends GetPacketStatusDepends; diff --git a/packages/napcat-onebot/action/file/online/ReceiveOnlineFile.ts b/packages/napcat-onebot/action/file/online/ReceiveOnlineFile.ts index aef09f5da..0cc2c8ab0 100644 --- a/packages/napcat-onebot/action/file/online/ReceiveOnlineFile.ts +++ b/packages/napcat-onebot/action/file/online/ReceiveOnlineFile.ts @@ -20,7 +20,7 @@ export class ReceiveOnlineFile extends OneBotAction; @@ -39,6 +39,10 @@ export default class GetFriendMsgHistory extends OneBotAction { // 处理参数 + const count = payload.count!; + const reverseOrder = payload.reverse_order! || payload.reverseOrder!; + const parseMultMsg = payload.parse_mult_msg!; + const disableGetUrl = payload.disable_get_url!; const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString()); if (!uid) throw new Error(`记录${payload.user_id}不存在`); const friend = await this.core.apis.FriendApi.isBuddy(uid); @@ -46,8 +50,8 @@ export default class GetFriendMsgHistory extends OneBotAction { @@ -55,7 +59,7 @@ export default class GetFriendMsgHistory extends OneBotAction this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url))) + msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl))) ).filter((msg): msg is OB11Message => msg !== undefined); return { messages: ob11MsgList }; } diff --git a/packages/napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder.ts b/packages/napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder.ts index 8fc45483d..00796225d 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetGroupFilesByFolder.ts @@ -8,7 +8,7 @@ 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: '文件数量' }), + file_count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' })), }); type PayloadType = Static; @@ -33,7 +33,7 @@ export class GetGroupFilesByFolder extends OneBotAction async _handle (payload: PayloadType): Promise { const retRaw = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), { sortType: 1, - fileCount: +payload.file_count, + fileCount: +payload.file_count!, startIndex: 0, sortOrder: 2, showOnlinedocFolder: 0, diff --git a/packages/napcat-onebot/action/go-cqhttp/GetGroupMsgHistory.ts b/packages/napcat-onebot/action/go-cqhttp/GetGroupMsgHistory.ts index a5718edac..459fdd442 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetGroupMsgHistory.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetGroupMsgHistory.ts @@ -10,12 +10,12 @@ import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples'; 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: '是否反向排序(旧版本兼容)' }), + count: Type.Optional(Type.Number({ default: 20, description: '获取消息数量' })), + reverse_order: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序' })), + disable_get_url: Type.Optional(Type.Boolean({ default: false, description: '是否禁用获取URL' })), + parse_mult_msg: Type.Optional(Type.Boolean({ default: true, description: '是否解析合并消息' })), + quick_reply: Type.Optional(Type.Boolean({ default: false, description: '是否快速回复' })), + reverseOrder: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' })), }); type PayloadType = Static; @@ -37,13 +37,18 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction { + const count = payload.count!; + const reverseOrder = payload.reverse_order! || payload.reverseOrder!; + const parseMultMsg = payload.parse_mult_msg!; + const disableGetUrl = payload.disable_get_url!; + const quickReply = payload.quick_reply!; 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'); // 拉取消息 const startMsgId = hasMessageSeq ? (MessageUnique.getMsgIdAndPeerByShortId(+payload.message_seq!)?.MsgId ?? payload.message_seq!.toString()) : '0'; const msgList = hasMessageSeq - ? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +payload.count, payload.reverse_order || payload.reverseOrder)).msgList - : (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +payload.count)).msgList; + ? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +count, reverseOrder)).msgList + : (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList; if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`); // 转换序号 await Promise.all(msgList.map(async msg => { @@ -51,7 +56,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply))) + msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl, quickReply))) ).filter((msg): msg is OB11Message => msg !== undefined); return { messages: ob11MsgList }; } diff --git a/packages/napcat-onebot/action/go-cqhttp/GetGroupRootFiles.ts b/packages/napcat-onebot/action/go-cqhttp/GetGroupRootFiles.ts index cc20cf5f1..600eceb2c 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetGroupRootFiles.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetGroupRootFiles.ts @@ -6,7 +6,7 @@ import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples'; const PayloadSchema = Type.Object({ group_id: Type.String({ description: '群号' }), - file_count: Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' }), + file_count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' })), }); type PayloadType = Static; @@ -31,7 +31,7 @@ export class GetGroupRootFiles extends OneBotAction { async _handle (payload: PayloadType) { const ret = await this.core.apis.MsgApi.getGroupFileList(payload.group_id.toString(), { sortType: 1, - fileCount: +payload.file_count, + fileCount: +payload.file_count!, startIndex: 0, sortOrder: 2, showOnlinedocFolder: 0, diff --git a/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts b/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts index 071e41792..6bf35250d 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts @@ -17,16 +17,14 @@ export class GetOnlineClient extends OneBotAction { override payloadSchema = PayloadSchema; override returnSchema = ReturnSchema; override actionSummary = '获取在线客户端'; - override actionDescription = '获取当前登录账号的在线客户端列表'; + override actionDescription = '获取当前登录账号的在线客户端列表;当前兼容实现返回空列表'; override actionTags = ['Go-CQHTTP']; override payloadExample = GoCQHTTPActionsExamples.GetOnlineClient.payload; override returnExample = GoCQHTTPActionsExamples.GetOnlineClient.response; - async _handle () { - // 注册监听 + async _handle (): Promise { this.core.apis.SystemApi.getOnlineDev(); await sleep(500); - return []; } } diff --git a/packages/napcat-onebot/action/go-cqhttp/GetStrangerInfo.ts b/packages/napcat-onebot/action/go-cqhttp/GetStrangerInfo.ts index 7610917ec..12f211dd1 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetStrangerInfo.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetStrangerInfo.ts @@ -8,7 +8,7 @@ import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples'; const PayloadSchema = Type.Object({ user_id: Type.String({ description: '用户QQ' }), - no_cache: Type.Union([Type.Boolean(), Type.String()], { default: false, description: '是否不使用缓存' }), + no_cache: Type.Optional(Type.Union([Type.Boolean(), Type.String()], { default: false, description: '是否不使用缓存' })), }); type PayloadType = Static; diff --git a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely.ts b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely.ts index 8683e2d6f..8d7afe736 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely.ts @@ -20,12 +20,12 @@ export class GoCQHTTPCheckUrlSafely extends OneBotAction { return { level: 1 }; } } diff --git a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts index 82c246977..f863c66a7 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts @@ -26,7 +26,12 @@ export class GoCQHTTPGetModelShow extends OneBotAction; + +const ReturnSchema = Type.Null(); + +type ReturnType = Static; // 兼容性代码 -export class GoCQHTTPSetModelShow extends OneBotAction { +export class GoCQHTTPSetModelShow extends OneBotAction { override actionName = ActionName.GoCQHTTP_SetModelShow; - override payloadSchema = Type.Object({}); - override returnSchema = Type.Null(); + override payloadSchema = PayloadSchema; + override returnSchema = ReturnSchema; override actionSummary = '设置机型'; - override actionDescription = '设置当前账号的设备机型名称'; + override actionDescription = '设置当前账号的设备机型名称;当前兼容实现不执行实际切换'; override actionTags = ['Go-CQHTTP']; - override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.payload; - override returnExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.response; - - async _handle () { + override payloadExample = {}; + override returnExample = null; + async _handle (): Promise { + return null; } } diff --git a/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts b/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts index 59de606f3..a636cf646 100644 --- a/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts +++ b/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts @@ -1,14 +1,34 @@ -import { OB11MessageMixType } from '@/napcat-onebot/types'; -import { ContextMode, normalize, ReturnDataType, SendMsgBase, SendMsgPayload } from '@/napcat-onebot/action/msg/SendMsg'; +import type { OB11MessageMixType } from '@/napcat-onebot/types'; +import { + ContextMode, + normalize, + ReturnDataType, + SendMsgBase, + SendMsgPayload, + SendMsgPayloadSchema, +} from '@/napcat-onebot/action/msg/SendMsg'; import { ActionName } from '@/napcat-onebot/action/router'; +import type { BaseCheckResult } from '@/napcat-onebot/action/router'; +import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message'; +import { Static, Type } from '@sinclair/typebox'; -// 未验证 -type GoCQHTTPSendForwardMsgPayload = SendMsgPayload & { messages?: OB11MessageMixType; }; +const GoCQHTTPSendForwardPayloadSchema = Type.Intersect([ + Type.Omit(SendMsgPayloadSchema, ['message']), + Type.Object({ + messages: OB11MessageMixTypeSchema, + }), +]); + +type GoCQHTTPSendForwardMsgPayload = Static & { + message?: OB11MessageMixType; +}; export class GoCQHTTPSendForwardMsgBase extends SendMsgBase { - protected override async check (payload: GoCQHTTPSendForwardMsgPayload) { - if (payload.messages) payload.message = normalize(payload.messages); - return super.check(payload); + override payloadSchema = GoCQHTTPSendForwardPayloadSchema; + + protected override getMessageForCheck (payload: SendMsgPayload): OB11MessageMixType { + const forwardPayload = payload as SendMsgPayload & GoCQHTTPSendForwardMsgPayload; + return normalize(forwardPayload.messages); } } export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase { @@ -24,11 +44,6 @@ export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase { override returnExample = { message_id: 123456, }; - - protected override async check (payload: GoCQHTTPSendForwardMsgPayload) { - if (payload.messages) payload.message = normalize(payload.messages); - return super.check(payload); - } } export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase { override actionName = ActionName.GoCQHTTP_SendPrivateForwardMsg; @@ -43,7 +58,18 @@ export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase { message_id: 123456, }; - override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise { + protected override async check (payload: SendMsgPayload): Promise { + payload.message_type = 'private'; + if (!payload.user_id) { + return { + valid: false, + message: '缺少参数 user_id', + }; + } + return super.check(payload); + } + + override async _handle (payload: SendMsgPayload): Promise { return this.base_handle(payload, ContextMode.Private); } } @@ -61,7 +87,18 @@ export class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase { message_id: 123456, }; - override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise { + protected override async check (payload: SendMsgPayload): Promise { + payload.message_type = 'group'; + if (!payload.group_id) { + return { + valid: false, + message: '缺少参数 group_id', + }; + } + return super.check(payload); + } + + override async _handle (payload: SendMsgPayload): Promise { return this.base_handle(payload, ContextMode.Group); } } diff --git a/packages/napcat-onebot/action/go-cqhttp/SendGroupNotice.ts b/packages/napcat-onebot/action/go-cqhttp/SendGroupNotice.ts index 9e7a54658..1e9a126a9 100644 --- a/packages/napcat-onebot/action/go-cqhttp/SendGroupNotice.ts +++ b/packages/napcat-onebot/action/go-cqhttp/SendGroupNotice.ts @@ -9,11 +9,11 @@ export const SendGroupNoticePayloadSchema = Type.Object({ group_id: Type.String({ description: '群号' }), content: Type.String({ description: '公告内容' }), image: Type.Optional(Type.String({ description: '公告图片路径或 URL' })), - pinned: Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否置顶 (0/1)' }), - type: Type.Union([Type.Number(), Type.String()], { default: 1, description: '类型 (默认为 1)' }), - confirm_required: Type.Union([Type.Number(), Type.String()], { default: 1, description: '是否需要确认 (0/1)' }), - is_show_edit_card: Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否显示修改群名片引导 (0/1)' }), - tip_window_type: Type.Union([Type.Number(), Type.String()], { default: 0, description: '弹窗类型 (默认为 0)' }), + pinned: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否置顶 (0/1)' })), + type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '类型 (默认为 1)' })), + confirm_required: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '是否需要确认 (0/1)' })), + is_show_edit_card: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否显示修改群名片引导 (0/1)' })), + tip_window_type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '弹窗类型 (默认为 0)' })), }); export type SendGroupNoticePayload = Static; @@ -29,6 +29,11 @@ export class SendGroupNotice extends OneBotAction override returnExample = GoCQHTTPActionsExamples.SendGroupNotice.response; async _handle (payload: SendGroupNoticePayload) { + const pinned = payload.pinned!; + const type = payload.type!; + const confirmRequired = payload.confirm_required!; + const showEditCard = payload.is_show_edit_card!; + const tipWindowType = payload.tip_window_type!; let UploadImage: { id: string, width: number, height: number; } | undefined; if (payload.image) { // 公告图逻辑 @@ -55,11 +60,11 @@ export class SendGroupNotice extends OneBotAction const publishGroupBulletinResult = await this.core.apis.WebApi.setGroupNotice( payload.group_id.toString(), payload.content, - +payload.pinned, - +payload.type, - +payload.is_show_edit_card, - +payload.tip_window_type, - +payload.confirm_required, + +pinned, + +type, + +showEditCard, + +tipWindowType, + +confirmRequired, UploadImage?.id, UploadImage?.width, UploadImage?.height diff --git a/packages/napcat-onebot/action/go-cqhttp/UploadGroupFile.ts b/packages/napcat-onebot/action/go-cqhttp/UploadGroupFile.ts index fde2b349b..1cf7fe42e 100644 --- a/packages/napcat-onebot/action/go-cqhttp/UploadGroupFile.ts +++ b/packages/napcat-onebot/action/go-cqhttp/UploadGroupFile.ts @@ -13,7 +13,7 @@ export const GoCQHTTPUploadGroupFilePayloadSchema = Type.Object({ name: Type.String({ description: '文件名' }), folder: Type.Optional(Type.String({ description: '父目录 ID' })), folder_id: Type.Optional(Type.String({ description: '父目录 ID (兼容性字段)' })), // 临时扩展 - upload_file: Type.Boolean({ default: true, description: '是否执行上传' }), + upload_file: Type.Optional(Type.Boolean({ default: true, description: '是否执行上传' })), }); export type GoCQHTTPUploadGroupFilePayload = Static; diff --git a/packages/napcat-onebot/action/go-cqhttp/UploadPrivateFile.ts b/packages/napcat-onebot/action/go-cqhttp/UploadPrivateFile.ts index 5375feade..aecef93ee 100644 --- a/packages/napcat-onebot/action/go-cqhttp/UploadPrivateFile.ts +++ b/packages/napcat-onebot/action/go-cqhttp/UploadPrivateFile.ts @@ -12,7 +12,7 @@ export const GoCQHTTPUploadPrivateFilePayloadSchema = Type.Object({ user_id: Type.String({ description: '用户 QQ' }), file: Type.String({ description: '资源路径或URL' }), name: Type.String({ description: '文件名' }), - upload_file: Type.Boolean({ default: true, description: '是否执行上传' }), + upload_file: Type.Optional(Type.Boolean({ default: true, description: '是否执行上传' })), }); export type GoCQHTTPUploadPrivateFilePayload = Static; diff --git a/packages/napcat-onebot/action/group/SendGroupMsg.ts b/packages/napcat-onebot/action/group/SendGroupMsg.ts index 0188af771..855d38443 100644 --- a/packages/napcat-onebot/action/group/SendGroupMsg.ts +++ b/packages/napcat-onebot/action/group/SendGroupMsg.ts @@ -15,6 +15,12 @@ class SendGroupMsg extends SendMsgBase { protected override async check (payload: SendMsgPayload): Promise { delete payload.user_id; payload.message_type = 'group'; + if (!payload.group_id) { + return { + valid: false, + message: '缺少参数 group_id', + }; + } return super.check(payload); } diff --git a/packages/napcat-onebot/action/group/SetGroupAddRequest.ts b/packages/napcat-onebot/action/group/SetGroupAddRequest.ts index 2f47f1275..2d8b655b6 100644 --- a/packages/napcat-onebot/action/group/SetGroupAddRequest.ts +++ b/packages/napcat-onebot/action/group/SetGroupAddRequest.ts @@ -31,8 +31,7 @@ export default class SetGroupAddRequest extends OneBotAction { const flag = payload.flag.toString(); const approve = payload.approve?.toString() !== 'false'; - const reason = payload.reason ?? ' '; - const count = payload.count; + const count = payload.count!; const invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(flag); const { doubt, notify } = invite_notify ? { @@ -47,12 +46,12 @@ export default class SetGroupAddRequest extends OneBotAction { diff --git a/packages/napcat-onebot/action/group/SetGroupBan.ts b/packages/napcat-onebot/action/group/SetGroupBan.ts index 1e0d714c6..723e56acf 100644 --- a/packages/napcat-onebot/action/group/SetGroupBan.ts +++ b/packages/napcat-onebot/action/group/SetGroupBan.ts @@ -7,7 +7,7 @@ import { GroupActionsExamples } from '../example/GroupActionsExamples'; const PayloadSchema = Type.Object({ group_id: Type.String({ description: '群号' }), user_id: Type.String({ description: '用户QQ' }), - duration: Type.Union([Type.Number(), Type.String()], { default: 0, description: '禁言时长(秒)' }), + duration: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '禁言时长(秒)' })), }); type PayloadType = Static; @@ -33,7 +33,7 @@ export default class SetGroupBan extends OneBotAction { if (member_role === 4) throw new Error('cannot ban owner'); // 例如无管理员权限时 result为 120101005 errMsg为 'ERR_NOT_GROUP_ADMIN' const ret = await this.core.apis.GroupApi.banMember(payload.group_id.toString(), - [{ uid, timeStamp: +payload.duration }]); + [{ uid, timeStamp: +payload.duration! }]); if (ret.result !== 0) throw new Error(ret.errMsg); return null; } diff --git a/packages/napcat-onebot/action/group/SetGroupLeave.ts b/packages/napcat-onebot/action/group/SetGroupLeave.ts index b7f0dc010..b6dda41bb 100644 --- a/packages/napcat-onebot/action/group/SetGroupLeave.ts +++ b/packages/napcat-onebot/action/group/SetGroupLeave.ts @@ -20,13 +20,21 @@ export default class SetGroupLeave extends OneBotAction override payloadSchema = PayloadSchema; override returnSchema = ReturnSchema; override actionSummary = '退出群组'; - override actionDescription = '退出或解散指定群聊'; + override actionDescription = '退出指定群聊;群主可通过 is_dismiss=true 解散群聊'; override actionTags = ['群组接口']; override payloadExample = GroupActionsExamples.SetGroupLeave.payload; override returnExample = GroupActionsExamples.SetGroupLeave.response; async _handle (payload: PayloadType): Promise { - await this.core.apis.GroupApi.quitGroup(payload.group_id.toString()); + const isDismiss = typeof payload.is_dismiss === 'string' + ? payload.is_dismiss === 'true' + : !!payload.is_dismiss; + + if (isDismiss) { + await this.core.apis.GroupApi.destroyGroup(payload.group_id.toString()); + } else { + await this.core.apis.GroupApi.quitGroup(payload.group_id.toString()); + } return null; } } diff --git a/packages/napcat-onebot/action/guild/GetGuildList.ts b/packages/napcat-onebot/action/guild/GetGuildList.ts index c15d7f7ea..b78b6ce1e 100644 --- a/packages/napcat-onebot/action/guild/GetGuildList.ts +++ b/packages/napcat-onebot/action/guild/GetGuildList.ts @@ -1,20 +1,27 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; import { ActionName } from '@/napcat-onebot/action/router'; -import { Type } from '@sinclair/typebox'; -import { GuildActionsExamples } from '../example/GuildActionsExamples'; +import { Static, Type } from '@sinclair/typebox'; -export class GetGuildList extends OneBotAction { +const PayloadSchema = Type.Object({}); + +type PayloadType = Static; + +const ReturnSchema = Type.Null(); + +type ReturnType = Static; + +export class GetGuildList extends OneBotAction { override actionName = ActionName.GetGuildList; - override payloadSchema = Type.Object({}); - override returnSchema = Type.Null(); + override payloadSchema = PayloadSchema; + override returnSchema = ReturnSchema; override actionSummary = '获取频道列表'; - override actionDescription = '获取当前帐号已加入的频道列表'; + override actionDescription = '获取当前帐号已加入的频道列表;当前兼容实现返回空结果'; override actionTags = ['频道接口']; - override payloadExample = GuildActionsExamples.GetGuildList.payload; - override returnExample = GuildActionsExamples.GetGuildList.response; - - async _handle (): Promise { + override payloadExample = {}; + override returnExample = null; + async _handle (): Promise { + return null; } } diff --git a/packages/napcat-onebot/action/guild/GetGuildProfile.ts b/packages/napcat-onebot/action/guild/GetGuildProfile.ts index 4985aa9f9..2f8993120 100644 --- a/packages/napcat-onebot/action/guild/GetGuildProfile.ts +++ b/packages/napcat-onebot/action/guild/GetGuildProfile.ts @@ -1,20 +1,27 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; import { ActionName } from '@/napcat-onebot/action/router'; -import { Type } from '@sinclair/typebox'; -import { GuildActionsExamples } from '../example/GuildActionsExamples'; +import { Static, Type } from '@sinclair/typebox'; -export class GetGuildProfile extends OneBotAction { +const PayloadSchema = Type.Object({}); + +type PayloadType = Static; + +const ReturnSchema = Type.Null(); + +type ReturnType = Static; + +export class GetGuildProfile extends OneBotAction { override actionName = ActionName.GetGuildProfile; - override payloadSchema = Type.Object({}); - override returnSchema = Type.Null(); + override payloadSchema = PayloadSchema; + override returnSchema = ReturnSchema; override actionSummary = '获取频道个人信息'; - override actionDescription = '获取当前帐号在频道中的个人资料'; + override actionDescription = '获取当前帐号在频道中的个人资料;当前兼容实现返回空结果'; override actionTags = ['频道接口']; - override payloadExample = GuildActionsExamples.GetGuildProfile.payload; - override returnExample = GuildActionsExamples.GetGuildProfile.response; - - async _handle (): Promise { + override payloadExample = {}; + override returnExample = null; + async _handle (): Promise { + return null; } } diff --git a/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts b/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts index 98f99b9d9..89ebb3e73 100644 --- a/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts +++ b/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts @@ -15,6 +15,7 @@ type PayloadType = Static; const ReturnSchema = Type.Null({ description: '操作结果' }); type ReturnType = Static; +const EmptyPayloadSchema = Type.Object({}); class MarkMsgAsRead extends OneBotAction { override actionSummary = '标记消息已读'; @@ -82,8 +83,10 @@ export class GoCQHTTPMarkMsgAsRead extends MarkMsgAsRead { override actionSummary = '标记消息已读 (Go-CQHTTP)'; } -export class MarkAllMsgAsRead extends OneBotAction { +export class MarkAllMsgAsRead extends OneBotAction, null> { override actionName = ActionName._MarkAllMsgAsRead; + override payloadSchema = EmptyPayloadSchema; + override returnSchema = ReturnSchema; override actionSummary = '标记所有消息已读'; override actionTags = ['消息接口']; override payloadExample = {}; diff --git a/packages/napcat-onebot/action/msg/SendMsg.ts b/packages/napcat-onebot/action/msg/SendMsg.ts index ee20652fa..ba4f26d53 100644 --- a/packages/napcat-onebot/action/msg/SendMsg.ts +++ b/packages/napcat-onebot/action/msg/SendMsg.ts @@ -1,6 +1,8 @@ import { - OB11MessageData, OB11MessageDataType, +} from '@/napcat-onebot/types'; +import type { + OB11MessageData, OB11MessageMixType, OB11MessageNode, OB11PostContext, @@ -8,16 +10,17 @@ import { import { ActionName, BaseCheckResult } from '@/napcat-onebot/action/router'; import { decodeCQCode } from '@/napcat-onebot/helper/cqcode'; import { MessageUnique } from 'napcat-common/src/message-unique'; -import { ChatType, ElementType, NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from 'napcat-core'; +import { ChatType, ElementType } from 'napcat-core'; +import type { NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from 'napcat-core'; import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder'; import { stringifyWithBigInt } from 'napcat-common/src/helper'; -import { PacketMsg } from 'napcat-core/packet/message/message'; -import { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter'; -import { Static, Type } from '@sinclair/typebox'; +import type { PacketMsg } from 'napcat-core/packet/message/message'; +import type { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter'; +import { Static, TSchema, Type } from '@sinclair/typebox'; import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples'; import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message'; -import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2'; +import type { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2'; export const SendMsgPayloadSchema = Type.Object({ message_type: Type.Optional(Type.Union([Type.Literal('private'), Type.Literal('group')], { description: '消息类型 (private/group)' })), @@ -48,15 +51,43 @@ export enum ContextMode { Group = 2, } +function normalizeMessageSegments (messages: OB11MessageData[]): OB11MessageData[] { + return messages.map((message) => { + if (message.type !== OB11MessageDataType.node) { + return message; + } + + if ('id' in message.data) { + return { + ...message, + data: { + ...message.data, + id: message.data.id.toString(), + }, + }; + } + + return { + ...message, + data: { + ...message.data, + content: normalize((message.data.content ?? []) as OB11MessageMixType), + }, + }; + }); +} + // Normalizes a mixed type (CQCode/a single segment/segment array) into a segment array. export function normalize (message: OB11MessageMixType, autoEscape = false): OB11MessageData[] { - return typeof message === 'string' + const normalized: OB11MessageData[] = typeof message === 'string' ? ( autoEscape - ? [{ type: OB11MessageDataType.text, data: { text: message } }] + ? [{ type: OB11MessageDataType.text, data: { text: message } } as OB11MessageData] : decodeCQCode(message) ) : Array.isArray(message) ? message : [message]; + + return normalizeMessageSegments(normalized); } export async function createContext (core: NapCatCore, payload: OB11PostContext | undefined, contextMode: ContextMode = ContextMode.Normal): Promise { @@ -127,12 +158,26 @@ function isNode (msg: OB11MessageData): msg is OB11MessageNode { return msg.type === OB11MessageDataType.node; } +function hasNodeReferenceId (msg: OB11MessageNode): msg is OB11MessageNode & { data: { id: string; }; } { + return 'id' in msg.data && typeof msg.data.id === 'string' && msg.data.id.length > 0; +} + export class SendMsgBase extends OneBotAction { - override payloadSchema = SendMsgPayloadSchema; - override returnSchema = SendMsgReturnSchema; + override payloadSchema: TSchema = SendMsgPayloadSchema; + override returnSchema: TSchema = SendMsgReturnSchema; override actionTags = ['消息接口']; + protected getMessageForCheck (payload: SendMsgPayload): OB11MessageMixType { + return payload.message; + } + protected override async check (payload: SendMsgPayload): Promise { + const base = await super.check(payload); + if (!base.valid) { + return base; + } + + payload.message = this.getMessageForCheck(payload); const messages = normalize(payload.message); const nodeElementLength = getSpecialMsgNum(messages, OB11MessageDataType.node); if (nodeElementLength > 0 && nodeElementLength !== messages.length) { @@ -225,8 +270,8 @@ export class SendMsgBase extends OneBotAction { this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!'); break; } - if (!node.data.id) { - const OB11Data = normalize(node.type === OB11MessageDataType.node ? node.data.content : node); + if (!hasNodeReferenceId(node)) { + const OB11Data = normalize(node.data.content); let sendElements: SendMessageElement[]; const subNodeMessages = OB11Data.filter(isNode); @@ -260,7 +305,7 @@ export class SendMsgBase extends OneBotAction { const transformedMsg = this.core.apis.PacketApi.pkt.msgConverter.rawMsgWithSendMsgToPacketMsg(packetMsgElements); this.core.context.logger.logDebug(`handleForwardedNodesPacket[SendRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`); packetMsg.push(transformedMsg); - } else if (node.data.id) { + } else { const id = node.data.id; const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(+id) || MessageUnique.getPeerByMsgId(id); if (!nodeMsg) { @@ -307,8 +352,6 @@ export class SendMsgBase extends OneBotAction { this.core.context.logger.logDebug(`handleForwardedNodesPacket[PureRaw] 转换为 ${stringifyWithBigInt(transformedMsg)}`); packetMsg.push(transformedMsg); } - } else { - this.core.context.logger.logDebug(`handleForwardedNodesPacket 跳过元素 ${stringifyWithBigInt(node)}`); } } if (packetMsg.length === 0) { @@ -369,8 +412,8 @@ export class SendMsgBase extends OneBotAction { }; let nodeMsgIds: string[] = []; for (const messageNode of messageNodes) { - const nodeId = messageNode.data.id; - if (nodeId) { + if (hasNodeReferenceId(messageNode)) { + const nodeId = messageNode.data.id; // 对Msgid和OB11ID混用情况兜底 const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(nodeId)) || MessageUnique.getPeerByMsgId(nodeId); if (!nodeMsg) { diff --git a/packages/napcat-onebot/action/msg/SendPrivateMsg.ts b/packages/napcat-onebot/action/msg/SendPrivateMsg.ts index 6dfea5122..93b521b12 100644 --- a/packages/napcat-onebot/action/msg/SendPrivateMsg.ts +++ b/packages/napcat-onebot/action/msg/SendPrivateMsg.ts @@ -18,6 +18,12 @@ class SendPrivateMsg extends SendMsgBase { protected override async check (payload: SendMsgPayload): Promise { payload.message_type = 'private'; + if (!payload.user_id) { + return { + valid: false, + message: '缺少参数 user_id', + }; + } return super.check(payload); } diff --git a/packages/napcat-onebot/action/new/GetDoubtFriendsAddRequest.ts b/packages/napcat-onebot/action/new/GetDoubtFriendsAddRequest.ts index 444c97c2e..bbc750e1f 100644 --- a/packages/napcat-onebot/action/new/GetDoubtFriendsAddRequest.ts +++ b/packages/napcat-onebot/action/new/GetDoubtFriendsAddRequest.ts @@ -4,7 +4,7 @@ import { Static, Type } from '@sinclair/typebox'; import { NewActionsExamples } from '../example/NewActionsExamples'; export const GetDoubtFriendsAddRequestPayloadSchema = Type.Object({ - count: Type.Number({ default: 50, description: '获取数量' }), + count: Type.Optional(Type.Number({ default: 50, description: '获取数量' })), }); export type GetDoubtFriendsAddRequestPayload = Static; @@ -20,6 +20,6 @@ export class GetDoubtFriendsAddRequest extends OneBotAction; @@ -16,11 +13,10 @@ export class SetDoubtFriendsAddRequest extends OneBotAction = T & StreamPacketBasic; -export enum StreamStatus { - Stream = 'stream', // 分片流数据包 - Response = 'response', // 流最终响应 - Reset = 'reset', // 重置流 - Error = 'error', // 流错误 -} +import { StreamPacket } from './StreamTypes'; + +export type { StreamPacketBasic, StreamPacket } from './StreamTypes'; +export { StreamStatus } from './StreamTypes'; + export abstract class BasicStream extends OneBotAction> { abstract override _handle (_payload: T, _adaptername: string, _config: NetworkAdapterConfig, req: OneBotRequestToolkit): Promise>; } diff --git a/packages/napcat-onebot/action/stream/StreamTypes.ts b/packages/napcat-onebot/action/stream/StreamTypes.ts new file mode 100644 index 000000000..25e286615 --- /dev/null +++ b/packages/napcat-onebot/action/stream/StreamTypes.ts @@ -0,0 +1,13 @@ +export type StreamPacketBasic = { + type: StreamStatus; + data_type?: string; +}; + +export type StreamPacket = T & StreamPacketBasic; + +export enum StreamStatus { + Stream = 'stream', // 分片流数据包 + Response = 'response', // 流最终响应 + Reset = 'reset', // 重置流 + Error = 'error', // 流错误 +} diff --git a/packages/napcat-onebot/action/stream/TestStreamDownload.ts b/packages/napcat-onebot/action/stream/TestStreamDownload.ts index 4b788dbc1..0c07a8d49 100644 --- a/packages/napcat-onebot/action/stream/TestStreamDownload.ts +++ b/packages/napcat-onebot/action/stream/TestStreamDownload.ts @@ -15,7 +15,7 @@ export class TestDownloadStream extends OneBotAction; diff --git a/packages/napcat-onebot/action/system/GetSystemMsg.ts b/packages/napcat-onebot/action/system/GetSystemMsg.ts index dd70172a8..4d0cdbd70 100644 --- a/packages/napcat-onebot/action/system/GetSystemMsg.ts +++ b/packages/napcat-onebot/action/system/GetSystemMsg.ts @@ -5,7 +5,7 @@ import { Static, Type } from '@sinclair/typebox'; import { OB11NotifySchema } from '../schemas'; export const GetGroupSystemMsgPayloadSchema = Type.Object({ - count: Type.Union([Type.Number(), Type.String()], { default: 50, description: '获取的消息数量' }), + count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '获取的消息数量' })), }); export type GetGroupSystemMsgPayload = Static; @@ -36,7 +36,7 @@ export class GetGroupSystemMsg extends OneBotAction { - const SingleScreenNotifies = await this.core.apis.GroupApi.getSingleScreenNotifies(false, +params.count); + const SingleScreenNotifies = await this.core.apis.GroupApi.getSingleScreenNotifies(false, +params.count!); const retData: GetGroupSystemMsgReturn = { invited_requests: [], InvitedRequest: [], join_requests: [] }; const notifyPromises = SingleScreenNotifies.map(async (SSNotify) => { diff --git a/packages/napcat-onebot/action/system/GetVersionInfo.ts b/packages/napcat-onebot/action/system/GetVersionInfo.ts index c2f15e9e9..efa6638db 100644 --- a/packages/napcat-onebot/action/system/GetVersionInfo.ts +++ b/packages/napcat-onebot/action/system/GetVersionInfo.ts @@ -3,6 +3,10 @@ import { ActionName } from '@/napcat-onebot/action/router'; import { napCatVersion } from 'napcat-common/src/version'; import { Type, Static } from '@sinclair/typebox'; +const PayloadSchema = Type.Object({}); + +type PayloadType = Static; + const ReturnSchema = Type.Object({ app_name: Type.String({ description: '应用名称' }), protocol_version: Type.String({ description: '协议版本' }), @@ -11,8 +15,9 @@ const ReturnSchema = Type.Object({ type ReturnType = Static; -export default class GetVersionInfo extends OneBotAction { +export default class GetVersionInfo extends OneBotAction { override actionName = ActionName.GetVersionInfo; + override payloadSchema = PayloadSchema; override returnSchema = ReturnSchema; override actionSummary = '获取版本信息'; override actionDescription = '获取版本信息'; diff --git a/packages/napcat-onebot/action/user/GetRecentContact.ts b/packages/napcat-onebot/action/user/GetRecentContact.ts index 15da1e1bf..376c794fc 100644 --- a/packages/napcat-onebot/action/user/GetRecentContact.ts +++ b/packages/napcat-onebot/action/user/GetRecentContact.ts @@ -4,7 +4,7 @@ import { NetworkAdapterConfig } from '@/napcat-onebot/config/config'; import { Static, Type } from '@sinclair/typebox'; export const GetRecentContactPayloadSchema = Type.Object({ - count: Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取的数量' }), + count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取的数量' })), }); export type GetRecentContactPayload = Static; @@ -45,7 +45,7 @@ export default class GetRecentContact extends OneBotAction { - const ret = await this.core.apis.UserApi.getRecentContactListSnapShot(+payload.count); + const ret = await this.core.apis.UserApi.getRecentContactListSnapShot(+payload.count!); // 烘焙消息 const results = await Promise.all(ret.info.changedList.map(async (t) => { const FastMsg = await this.core.apis.MsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]); diff --git a/packages/napcat-onebot/action/user/SendLike.ts b/packages/napcat-onebot/action/user/SendLike.ts index 869bc919e..e0708a750 100644 --- a/packages/napcat-onebot/action/user/SendLike.ts +++ b/packages/napcat-onebot/action/user/SendLike.ts @@ -3,7 +3,7 @@ import { ActionName } from '@/napcat-onebot/action/router'; import { Static, Type } from '@sinclair/typebox'; export const SendLikePayloadSchema = Type.Object({ user_id: Type.String({ description: '对方 QQ 号' }), - times: Type.Union([Type.Number(), Type.String()], { default: 1, description: '点赞次数' }), + times: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '点赞次数' })), }); export type SendLikePayload = Static; @@ -28,7 +28,7 @@ export default class SendLike extends OneBotAction { async _handle (payload: SendLikePayload): Promise { const qq = payload.user_id.toString(); const uid: string = await this.core.apis.UserApi.getUidByUinV2(qq) ?? ''; - const result = await this.core.apis.UserApi.like(uid, +payload.times); + const result = await this.core.apis.UserApi.like(uid, +payload.times!); if (result.result !== 0) { throw new Error(`点赞失败 ${result.errMsg}`); } diff --git a/packages/napcat-onebot/types/message.ts b/packages/napcat-onebot/types/message.ts index c4b047ac4..68920df22 100644 --- a/packages/napcat-onebot/types/message.ts +++ b/packages/napcat-onebot/types/message.ts @@ -276,10 +276,16 @@ export const OB11MessageFlashTransferSchema = Type.Object({ // 但为了与原始类型完全兼容,我们使用 Type.Unknown 来表示递归部分 // 合并转发消息节点 -export const OB11MessageNodeSchema = Type.Object({ +export const OB11MessageNodeReferenceSchema = Type.Object({ + type: Type.Literal(OB11MessageDataType.node), + data: Type.Object({ + id: Type.String({ description: '转发消息ID', minLength: 1 }), + }, { additionalProperties: false }), +}, { description: '引用已有消息的合并转发节点' }); + +export const OB11MessageNodeInlineSchema = Type.Object({ type: Type.Literal(OB11MessageDataType.node), data: Type.Object({ - id: Type.Optional(Type.String({ description: '转发消息ID' })), user_id: Type.Optional(Type.Union([Type.Number(), Type.String()], { description: '发送者QQ号' })), uin: Type.Optional(Type.Union([Type.Number(), Type.String()], { description: '发送者QQ号(兼容go-cqhttp)' })), nickname: Type.String({ description: '发送者昵称' }), @@ -292,9 +298,14 @@ export const OB11MessageNodeSchema = Type.Object({ }))), summary: Type.Optional(Type.String({ description: '摘要' })), prompt: Type.Optional(Type.String({ description: '提示' })), - time: Type.Optional(Type.String({ description: '时间' })), - }), -}, { $id: 'OB11MessageNode', description: '合并转发消息节点' }); + time: Type.Optional(Type.Union([Type.String({ description: '时间' }), Type.Number({ description: '时间' })])), + }, { additionalProperties: false }), +}, { description: '内联合并转发消息节点' }); + +export const OB11MessageNodeSchema = Type.Union([ + OB11MessageNodeReferenceSchema, + OB11MessageNodeInlineSchema, +], { $id: 'OB11MessageNode', description: '合并转发消息节点' }); // 合并转发消息段 export const OB11MessageForwardSchema = Type.Object({ @@ -434,7 +445,9 @@ export type OB11MessageJson = Static; export type OB11MessageXml = Static; export type OB11MessageMarkdown = Static; export type OB11MessageMiniApp = Static; -export type OB11MessageNode = Static; +export type OB11MessageNodeReference = Static; +export type OB11MessageNodeInline = Static; +export type OB11MessageNode = OB11MessageNodeReference | OB11MessageNodeInline; export type OB11MessageForward = Static; export type OB11MessageOnlineFile = Static; export type OB11MessageFlashTransfer = Static; @@ -447,7 +460,7 @@ export type OB11Message = Static; // 合并转发消息节点纯文本接口定义 export type OB11MessageNodePlain = OB11MessageNode & { - data: { + data: OB11MessageNode['data'] & { content?: Array; message: Array; }; diff --git a/packages/napcat-schema/index.ts b/packages/napcat-schema/index.ts index eb98095cf..d89522a8a 100644 --- a/packages/napcat-schema/index.ts +++ b/packages/napcat-schema/index.ts @@ -21,6 +21,8 @@ interface ActionSchemaInfo { tags?: string[]; payloadExample?: unknown; returnExample?: unknown; + supported?: boolean; + unsupportedReason?: string; errorExamples?: Array<{ code: number, description: string; }>; } @@ -490,6 +492,8 @@ export function initSchemas () { tags: action.actionTags, payloadExample: action.payloadExample, returnExample: action.returnExample, + supported: action.supported, + unsupportedReason: action.unsupportedReason, errorExamples: action.errorExamples, }; }); @@ -509,6 +513,8 @@ export function initSchemas () { tags: action.actionTags, payloadExample: action.payloadExample, returnExample: action.returnExample, + supported: action.supported, + unsupportedReason: action.unsupportedReason, errorExamples: action.errorExamples, }; }); @@ -570,6 +576,23 @@ function createOpenAPIDocument (): Record { } function buildResponseExamples (schemas: ActionSchemaInfo): Record { + if (schemas.supported === false) { + const reason = schemas.unsupportedReason ?? '当前版本未实现该接口'; + return { + Unsupported: { + summary: '未实现接口', + value: { + status: 'failed', + retcode: 200, + data: null, + message: reason, + wording: reason, + stream: 'normal-action', + }, + }, + }; + } + const successData = schemas.returnExample ?? {}; const examples: Record = { Success: isMeaninglessSuccessExampleData(successData) @@ -632,13 +655,17 @@ function appendActionPaths (openapi: Record) { paths[path] = { post: { - summary: schemas.summary || actionName, - deprecated: false, - description: schemas.description || '', + summary: schemas.supported === false ? `${schemas.summary || actionName} (未实现)` : (schemas.summary || actionName), + deprecated: schemas.supported === false, + description: schemas.unsupportedReason + ? `${schemas.description || ''}\n\n当前导出状态:未实现兼容接口,调用将返回业务错误。\n原因:${schemas.unsupportedReason}`.trim() + : (schemas.description || ''), tags: schemas.tags || [], + 'x-supported': schemas.supported !== false, + ...(schemas.unsupportedReason ? { 'x-unsupported-reason': schemas.unsupportedReason } : {}), parameters: [], requestBody: { - description: 'API 参数', + description: schemas.supported === false ? '兼容占位接口参数;当前版本调用将返回业务错误' : 'API 参数', content: { 'application/json': { schema: cleanPayload, diff --git a/packages/napcat-test/action-contract.test.ts b/packages/napcat-test/action-contract.test.ts new file mode 100644 index 000000000..116cd1599 --- /dev/null +++ b/packages/napcat-test/action-contract.test.ts @@ -0,0 +1,464 @@ +import { describe, expect, test, vi } from 'vitest'; + +import { GetOnlineClient } from '../napcat-onebot/action/go-cqhttp/GetOnlineClient'; +import { GoCQHTTPCheckUrlSafely } from '../napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely'; +import { GoCQHTTPSetModelShow } from '../napcat-onebot/action/go-cqhttp/GoCQHTTPSetModelShow'; +import GetFriendMsgHistory from '../napcat-onebot/action/go-cqhttp/GetFriendMsgHistory'; +import { GoCQHTTPSendForwardMsgBase } from '../napcat-onebot/action/go-cqhttp/SendForwardMsg'; +import { SendGroupNotice } from '../napcat-onebot/action/go-cqhttp/SendGroupNotice'; +import SetGroupAddRequest from '../napcat-onebot/action/group/SetGroupAddRequest'; +import SendGroupMsg from '../napcat-onebot/action/group/SendGroupMsg'; +import { GetGuildList } from '../napcat-onebot/action/guild/GetGuildList'; +import { GetGuildProfile } from '../napcat-onebot/action/guild/GetGuildProfile'; +import SetGroupLeave from '../napcat-onebot/action/group/SetGroupLeave'; +import SendPrivateMsg from '../napcat-onebot/action/msg/SendPrivateMsg'; +import SendLike from '../napcat-onebot/action/user/SendLike'; +import { OneBotAction } from '../napcat-onebot/action/OneBotAction'; +import { Static, Type } from '@sinclair/typebox'; + +vi.mock('napcat-core', () => ({ + ChatType: { + KCHATTYPEGROUP: 2, + KCHATTYPEC2C: 1, + KCHATTYPETEMPC2CFROMGROUP: 3, + }, + ElementType: { + TEXT: 'text', + PIC: 'pic', + REPLY: 'reply', + FILE: 'file', + VIDEO: 'video', + ARK: 'ark', + PTT: 'ptt', + }, + NapCatCore: class {}, +})); + +vi.mock('napcat-core/types', () => ({ + ChatType: { + KCHATTYPEGROUP: 2, + KCHATTYPEC2C: 1, + KCHATTYPETEMPC2CFROMGROUP: 3, + }, + NTGroupRequestOperateTypes: { + KAGREE: 'agree', + KREFUSE: 'refuse', + }, +})); + +function createCoreStub (overrides: Record = {}) { + return { + context: { + logger: { + logError: vi.fn(), + logDebug: vi.fn(), + logWarn: vi.fn(), + }, + }, + selfInfo: { + uin: '10001', + uid: 'u_10001', + }, + apis: {}, + ...overrides, + }; +} + +class ForwardMessagesOnlyAction extends GoCQHTTPSendForwardMsgBase { + override async _handle (payload: any) { + return { + message_id: 1, + normalized_message: payload.message, + } as any; + } +} + +class ForwardMixedNodeAction extends GoCQHTTPSendForwardMsgBase { + calls = 0; + + override async _handle () { + this.calls += 1; + return { message_id: 1 } as any; + } +} + +const DefaultedActionPayloadSchema = Type.Object({ + count: Type.Optional(Type.Number({ default: 20 })), + enabled: Type.Optional(Type.Boolean({ default: false })), +}); + +type DefaultedActionPayload = Static; + +class DefaultedPayloadAction extends OneBotAction { + override payloadSchema = DefaultedActionPayloadSchema; + override returnSchema = DefaultedActionPayloadSchema; + + override async _handle (payload: DefaultedActionPayload) { + return { + count: payload.count!, + enabled: payload.enabled!, + }; + } +} + +describe('NapCat Action Contracts', () => { + test('send_private_msg should reject payloads without message during websocket validation', async () => { + const action = new SendPrivateMsg({} as any, createCoreStub() as any); + + const response = await action.websocketHandle( + { user_id: '123456789' } as any, + null, + 'ws', + {} as any + ); + + expect(response.retcode).toBe(1400); + }); + + test('send_group_msg should reject payloads without group_id during websocket validation', async () => { + const action = new SendGroupMsg({} as any, createCoreStub() as any); + + const response = await action.websocketHandle( + { message: 'hello' } as any, + null, + 'ws', + {} as any + ); + + expect(response.retcode).toBe(1400); + expect(response.message).toContain('group_id'); + }); + + test('send_forward_msg should accept messages as the only message field', async () => { + const action = new ForwardMessagesOnlyAction({} as any, createCoreStub() as any); + const payload: Record = { + group_id: '123456', + messages: [{ + type: 'node', + data: { + id: '654321', + }, + }], + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(Array.isArray(payload['message'])).toBe(true); + expect(payload['message']).toEqual([{ + type: 'node', + data: { + id: '654321', + }, + }]); + }); + + test('send_forward_msg should copy parsed reference node ids into message', async () => { + const action = new ForwardMessagesOnlyAction({} as any, createCoreStub() as any); + const payload: Record = { + group_id: '123456', + messages: [{ + type: 'node', + data: { + id: 654321, + }, + }], + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(payload['message']).toEqual([{ + type: 'node', + data: { + id: '654321', + }, + }]); + expect((response.data as any).normalized_message).toEqual([{ + type: 'node', + data: { + id: '654321', + }, + }]); + }); + + test('send_forward_msg should normalize nested reference node ids recursively', async () => { + const action = new ForwardMessagesOnlyAction({} as any, createCoreStub() as any); + const payload: Record = { + group_id: '123456', + messages: [{ + type: 'node', + data: { + nickname: 'outer', + content: [{ + type: 'node', + data: { + id: 654321, + }, + }], + }, + }], + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(payload['message']).toEqual([{ + type: 'node', + data: { + nickname: 'outer', + content: [{ + type: 'node', + data: { + id: '654321', + }, + }], + }, + }]); + expect((response.data as any).normalized_message).toEqual(payload['message']); + }); + + test('send_forward_msg should fail mixed node payloads during check before _handle', async () => { + const action = new ForwardMixedNodeAction({} as any, createCoreStub() as any); + + const response = await action.websocketHandle({ + messages: [ + { type: 'node', data: { id: '123' } }, + { type: 'text', data: { text: 'hello' } }, + ], + } as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(1400); + expect(action.calls).toBe(0); + }); + + test('OneBotAction should pass TypeBox-defaulted payloads into _handle', async () => { + const action = new DefaultedPayloadAction({} as any, createCoreStub() as any); + const payload: Record = {}; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(response.data).toEqual({ + count: 20, + enabled: false, + }); + expect(payload).toEqual({ + count: 20, + enabled: false, + }); + }); + + test('send_like should inject default times before _handle uses non-null assertion', async () => { + const getUidByUinV2 = vi.fn().mockResolvedValue('u_123456'); + const like = vi.fn().mockResolvedValue({ result: 0, errMsg: '' }); + const action = new SendLike({} as any, createCoreStub({ + apis: { + UserApi: { + getUidByUinV2, + like, + }, + }, + }) as any); + const payload: Record = { + user_id: '123456', + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(like).toHaveBeenCalledWith('u_123456', 1); + expect(payload['times']).toBe(1); + }); + + test('send_group_notice should inject all default fields before _handle uses non-null assertions', async () => { + const setGroupNotice = vi.fn().mockResolvedValue({ ec: 0, em: '' }); + const action = new SendGroupNotice({} as any, createCoreStub({ + apis: { + WebApi: { + setGroupNotice, + }, + }, + }) as any); + const payload: Record = { + group_id: '123456', + content: 'hello', + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(setGroupNotice).toHaveBeenCalledWith( + '123456', + 'hello', + 0, + 1, + 0, + 0, + 1, + undefined, + undefined, + undefined + ); + expect(payload).toMatchObject({ + pinned: 0, + type: 1, + confirm_required: 1, + is_show_edit_card: 0, + tip_window_type: 0, + }); + }); + + test('get_friend_msg_history should inject default booleans and count before _handle uses non-null assertions', async () => { + const getUidByUinV2 = vi.fn().mockResolvedValue('u_123456'); + const isBuddy = vi.fn().mockResolvedValue(true); + const getAioFirstViewLatestMsgs = vi.fn().mockResolvedValue({ + msgList: [{ + chatType: 1, + peerUid: 'u_123456', + msgId: 'msg-1', + }], + }); + const parseMessage = vi.fn().mockResolvedValue({ type: 'text', data: { text: 'hello' } }); + const action = new GetFriendMsgHistory({ + apis: { + MsgApi: { + parseMessage, + }, + }, + } as any, createCoreStub({ + apis: { + UserApi: { + getUidByUinV2, + }, + FriendApi: { + isBuddy, + }, + MsgApi: { + getAioFirstViewLatestMsgs, + }, + }, + }) as any); + const payload: Record = { + user_id: '123456', + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', { messagePostFormat: 'array' } as any); + + expect(response.retcode).toBe(0); + expect(getAioFirstViewLatestMsgs).toHaveBeenCalledWith({ + chatType: 1, + peerUid: 'u_123456', + }, 20); + expect(parseMessage).toHaveBeenCalledWith( + expect.objectContaining({ msgId: 'msg-1' }), + 'array', + true, + false + ); + expect(payload).toMatchObject({ + count: 20, + reverse_order: false, + disable_get_url: false, + parse_mult_msg: true, + quick_reply: false, + reverseOrder: false, + }); + }); + + test('set_group_add_request should inject default count and reason before notify lookup', async () => { + const notify = { + seq: 'flag-1', + type: 1, + group: { + groupCode: '123456', + }, + }; + const getSingleScreenNotifies = vi.fn().mockResolvedValue([notify]); + const handleGroupRequest = vi.fn().mockResolvedValue(undefined); + const action = new SetGroupAddRequest({ + apis: { + MsgApi: { + notifyGroupInvite: new Map(), + }, + }, + } as any, createCoreStub({ + apis: { + GroupApi: { + getSingleScreenNotifies, + handleGroupRequest, + }, + }, + }) as any); + const payload: Record = { + flag: 'flag-1', + }; + + const response = await action.websocketHandle(payload as any, null, 'ws', {} as any); + + expect(response.retcode).toBe(0); + expect(getSingleScreenNotifies).toHaveBeenCalledWith(false, 100); + expect(handleGroupRequest).toHaveBeenCalledWith(false, notify, 'agree', ' '); + expect(payload).toMatchObject({ + count: 100, + reason: ' ', + }); + }); + + test('set_group_leave should call quitGroup unless is_dismiss is truthy', async () => { + const quitGroup = vi.fn(); + const destroyGroup = vi.fn(); + const action = new SetGroupLeave({} as any, createCoreStub({ + apis: { + GroupApi: { + quitGroup, + destroyGroup, + }, + }, + }) as any); + + await action._handle({ group_id: '123456', is_dismiss: false } as any); + expect(quitGroup).toHaveBeenCalledWith('123456'); + expect(destroyGroup).not.toHaveBeenCalled(); + + await action._handle({ group_id: '123456', is_dismiss: 'true' } as any); + expect(destroyGroup).toHaveBeenCalledWith('123456'); + }); + + test('compatibility actions should keep returning successful placeholder responses', async () => { + const getOnlineDev = vi.fn(); + const getOnlineClient = new GetOnlineClient({} as any, createCoreStub({ + apis: { + SystemApi: { + getOnlineDev, + }, + }, + }) as any); + const checkUrlSafely = new GoCQHTTPCheckUrlSafely({} as any, createCoreStub() as any); + const setModelShow = new GoCQHTTPSetModelShow({} as any, createCoreStub() as any); + const getGuildList = new GetGuildList({} as any, createCoreStub() as any); + const getGuildProfile = new GetGuildProfile({} as any, createCoreStub() as any); + + await expect(getOnlineClient.websocketHandle({} as any, null, 'ws', {} as any)).resolves.toMatchObject({ + retcode: 0, + data: [], + }); + expect(getOnlineDev).toHaveBeenCalled(); + await expect(checkUrlSafely.websocketHandle({ url: 'https://example.com' } as any, null, 'ws', {} as any)).resolves.toMatchObject({ + retcode: 0, + data: { level: 1 }, + }); + await expect(setModelShow.websocketHandle({} as any, null, 'ws', {} as any)).resolves.toMatchObject({ + retcode: 0, + data: null, + }); + await expect(getGuildList.websocketHandle({} as any, null, 'ws', {} as any)).resolves.toMatchObject({ + retcode: 0, + data: null, + }); + await expect(getGuildProfile.websocketHandle({} as any, null, 'ws', {} as any)).resolves.toMatchObject({ + retcode: 0, + data: null, + }); + }); +}); diff --git a/packages/napcat-test/schema.test.ts b/packages/napcat-test/schema.test.ts index 9cd9443b9..5f10850f3 100644 --- a/packages/napcat-test/schema.test.ts +++ b/packages/napcat-test/schema.test.ts @@ -1,12 +1,91 @@ -import { describe, expect, test } from 'vitest'; +import { describe, expect, test, vi } from 'vitest'; import { TypeCompiler } from '@sinclair/typebox/compiler'; import { Value } from '@sinclair/typebox/value'; import { Type } from '@sinclair/typebox'; -import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from '../napcat-onebot/types/message'; +import { OB11MessageDataSchema, OB11MessageNodeSchema, OB11MessageSchema, OB11PostSendMsgSchema } from '../napcat-onebot/types/message'; import { OB11MessageSchema as OB11ActionMessageSchema } from '../napcat-onebot/action/schemas'; +import { GoCQHTTPActionsExamples } from '../napcat-onebot/action/example/GoCQHTTPActionsExamples'; +import { GuildActionsExamples } from '../napcat-onebot/action/example/GuildActionsExamples'; import { OneBotConfigSchema, loadConfig as loadOneBotConfig, OneBotConfig } from '../napcat-onebot/config'; import { NapcatConfigSchema } from '../napcat-core/helper/config'; +import { GoCQHTTPSendForwardMsg, GoCQHTTPSendGroupForwardMsg, GoCQHTTPSendPrivateForwardMsg } from '../napcat-onebot/action/go-cqhttp/SendForwardMsg'; +import { GetOnlineClient } from '../napcat-onebot/action/go-cqhttp/GetOnlineClient'; +import { GoCQHTTPCheckUrlSafely } from '../napcat-onebot/action/go-cqhttp/GoCQHTTPCheckUrlSafely'; +import { GoCQHTTPGetModelShow } from '../napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow'; +import { GoCQHTTPSetModelShow } from '../napcat-onebot/action/go-cqhttp/GoCQHTTPSetModelShow'; +import { SetGroupAlbumMediaLike } from '../napcat-onebot/action/extends/SetGroupAlbumMediaLike'; +import { ReceiveOnlineFile } from '../napcat-onebot/action/file/online/ReceiveOnlineFile'; +import { GetGuildList } from '../napcat-onebot/action/guild/GetGuildList'; +import { GetGuildProfile } from '../napcat-onebot/action/guild/GetGuildProfile'; +import { MarkAllMsgAsRead } from '../napcat-onebot/action/msg/MarkMsgAsRead'; +import { SetDoubtFriendsAddRequest } from '../napcat-onebot/action/new/SetDoubtFriendsAddRequest'; +import { TestDownloadStream } from '../napcat-onebot/action/stream/TestStreamDownload'; +import GetVersionInfo from '../napcat-onebot/action/system/GetVersionInfo'; + +vi.mock('napcat-core', () => ({ + ChatType: { + KCHATTYPEGROUP: 2, + KCHATTYPEC2C: 1, + KCHATTYPETEMPC2CFROMGROUP: 3, + }, + ElementType: { + TEXT: 'text', + PIC: 'pic', + REPLY: 'reply', + FILE: 'file', + VIDEO: 'video', + ARK: 'ark', + PTT: 'ptt', + }, + NapCatCore: class {}, +})); + +vi.mock('napcat-core/types', () => ({ + ChatType: { + KCHATTYPEGROUP: 2, + KCHATTYPEC2C: 1, + KCHATTYPETEMPC2CFROMGROUP: 3, + }, +})); + +function hasTopLevelProperty (schema: unknown, key: string): boolean { + if (!schema || typeof schema !== 'object') { + return false; + } + + const typedSchema = schema as { + properties?: Record, + allOf?: unknown[], + anyOf?: unknown[], + oneOf?: unknown[], + }; + + if (typedSchema.properties && key in typedSchema.properties) { + return true; + } + + return ['allOf', 'anyOf', 'oneOf'].some((field) => { + const children = typedSchema[field as keyof typeof typedSchema]; + return Array.isArray(children) && children.some(child => hasTopLevelProperty(child, key)); + }); +} + +function createCoreStub () { + return { + context: { + logger: { + logError: vi.fn(), + logDebug: vi.fn(), + logWarn: vi.fn(), + }, + }, + } as any; +} + +function createAction (ActionClass: new (...args: any[]) => T): T { + return new ActionClass({} as any, createCoreStub()); +} describe('NapCat Schemas Compilation', () => { test('should compile OB11MessageDataSchema without duplicate id error', () => { @@ -63,6 +142,142 @@ describe('NapCat Schemas Validation & Coercion', () => { const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema); expect(compiler.Check(data)).toBe(true); }); + + test('should accept id-only forward nodes', () => { + const payload = { + type: 'node', + data: { + id: '123456', + }, + }; + + let data: unknown = structuredClone(payload); + data = Value.Parse(OB11MessageNodeSchema, data); + + const compiler = TypeCompiler.Compile(OB11MessageNodeSchema); + expect(compiler.Check(data)).toBe(true); + }); + + test('should reject forward reference nodes with empty id', () => { + const payload = { + type: 'node', + data: { + id: '', + }, + }; + + const compiler = TypeCompiler.Compile(OB11MessageNodeSchema); + expect(compiler.Check(payload)).toBe(false); + }); + + test('should accept inline forward nodes with numeric time', () => { + const payload = { + type: 'node', + data: { + nickname: 'QQ用户', + content: [{ type: 'text', data: { text: 'hello' } }], + time: 1741600000, + }, + }; + + let data: unknown = structuredClone(payload); + data = Value.Parse(OB11MessageNodeSchema, data); + + const compiler = TypeCompiler.Compile(OB11MessageNodeSchema); + expect(compiler.Check(data)).toBe(true); + }); + + test('should reject forward nodes that mix reference and inline payload fields', () => { + const payload = { + type: 'node', + data: { + id: '123456', + content: [{ type: 'text', data: { text: 'hello' } }], + }, + }; + + const compiler = TypeCompiler.Compile(OB11MessageNodeSchema); + expect(compiler.Check(payload)).toBe(false); + }); +}); + +describe('NapCat Action Metadata', () => { + test('should export messages alias in forward message action schemas', () => { + const actions = [ + createAction(GoCQHTTPSendForwardMsg), + createAction(GoCQHTTPSendPrivateForwardMsg), + createAction(GoCQHTTPSendGroupForwardMsg), + ]; + + for (const action of actions) { + expect(hasTopLevelProperty((action as any).payloadSchema, 'messages')).toBe(true); + expect(hasTopLevelProperty((action as any).payloadSchema, 'message')).toBe(false); + } + }); + + test('should remove dead payload fields from action schemas', () => { + const doubtFriendAction = createAction(SetDoubtFriendsAddRequest); + const albumLikeAction = createAction(SetGroupAlbumMediaLike); + + expect(hasTopLevelProperty((doubtFriendAction as any).payloadSchema, 'approve')).toBe(false); + expect(hasTopLevelProperty((albumLikeAction as any).payloadSchema, 'set')).toBe(false); + }); + + test('should keep examples aligned with fixed action contracts', () => { + const receiveOnlineFileAction = createAction(ReceiveOnlineFile); + const testStreamDownloadAction = createAction(TestDownloadStream); + const getModelShowAction = createAction(GoCQHTTPGetModelShow); + + expect((receiveOnlineFileAction as any).payloadExample).toEqual({ + user_id: '123456789', + msg_id: '123', + element_id: '456', + }); + expect((testStreamDownloadAction as any).payloadExample).toEqual({ error: false }); + expect((getModelShowAction as any).returnExample).toEqual([{ + variants: { + model_show: 'napcat', + need_pay: false, + }, + }]); + }); + + test('should keep compatibility placeholder metadata aligned with runtime responses', () => { + const compatibilityActions = [ + createAction(GoCQHTTPCheckUrlSafely), + createAction(GetOnlineClient), + createAction(GoCQHTTPSetModelShow), + createAction(GetGuildList), + createAction(GetGuildProfile), + ]; + + for (const action of compatibilityActions) { + expect((action as any).supported).toBe(true); + expect((action as any).unsupportedReason).toBeUndefined(); + } + + expect(GoCQHTTPActionsExamples.GetOnlineClient.payload).toEqual({}); + expect(GoCQHTTPActionsExamples.GetOnlineClient.response).toEqual([]); + expect(GoCQHTTPActionsExamples.GoCQHTTPCheckUrlSafely.response).toEqual({ level: 1 }); + expect(GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.payload).toEqual({}); + expect(GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.response).toEqual(null); + expect(GuildActionsExamples.GetGuildList).toEqual({ payload: {}, response: null }); + expect(GuildActionsExamples.GetGuildProfile).toEqual({ payload: {}, response: null }); + + expect((createAction(GetOnlineClient) as any).returnSchema).toMatchObject({ type: 'array' }); + expect((createAction(GoCQHTTPCheckUrlSafely) as any).returnExample).toEqual({ level: 1 }); + expect((createAction(GoCQHTTPSetModelShow) as any).returnSchema).toMatchObject({ type: 'null' }); + expect((createAction(GetGuildList) as any).returnSchema).toMatchObject({ type: 'null' }); + expect((createAction(GetGuildProfile) as any).returnSchema).toMatchObject({ type: 'null' }); + }); + + test('should add explicit empty payload schemas to no-arg actions', () => { + const getVersionInfoAction = createAction(GetVersionInfo); + const markAllMsgAsReadAction = createAction(MarkAllMsgAsRead); + + expect((getVersionInfoAction as any).payloadSchema).toMatchObject({ type: 'object' }); + expect((markAllMsgAsReadAction as any).payloadSchema).toMatchObject({ type: 'object' }); + }); }); describe('NapCat Configuration Loaders', () => { diff --git a/packages/napcat-test/vitest.config.ts b/packages/napcat-test/vitest.config.ts index 7dc4f8369..f75c9652c 100644 --- a/packages/napcat-test/vitest.config.ts +++ b/packages/napcat-test/vitest.config.ts @@ -13,6 +13,8 @@ export default defineConfig({ '@/napcat-test': resolve(__dirname, '.'), '@/napcat-common': resolve(__dirname, '../napcat-common'), '@/napcat-core': resolve(__dirname, '../napcat-core'), + '@/napcat-onebot': resolve(__dirname, '../napcat-onebot'), + '@/napcat-schema': resolve(__dirname, '../napcat-schema'), }, }, });