diff --git a/packages/napcat-core/apis/group.ts b/packages/napcat-core/apis/group.ts index 3b6cc08d8..2b3c17e95 100644 --- a/packages/napcat-core/apis/group.ts +++ b/packages/napcat-core/apis/group.ts @@ -445,10 +445,6 @@ 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 a7745f400..4619da01f 100644 --- a/packages/napcat-onebot/action/OneBotAction.ts +++ b/packages/napcat-onebot/action/OneBotAction.ts @@ -1,12 +1,11 @@ import { ActionName, BaseCheckResult } from './router'; import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler'; import { Value } from '@sinclair/typebox/value'; -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'; +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'; export const ActionExamples = { Common: { errors: [ @@ -58,8 +57,6 @@ 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 d29315feb..32c19604d 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: {}, + payload: { no_cache: false }, response: [], }, GoCQHTTPCheckUrlSafely: { @@ -69,16 +69,11 @@ export const GoCQHTTPActionsExamples = { }, GoCQHTTPGetModelShow: { payload: { model: 'iPhone 13' }, - response: [{ - variants: { - model_show: 'napcat', - need_pay: false, - }, - }], + response: { variants: [] }, }, GoCQHTTPSetModelShow: { - payload: {}, - response: null, + payload: { model: 'iPhone 13', model_show: 'iPhone 13' }, + response: {}, }, QuickAction: { payload: { context: {}, operation: {} }, diff --git a/packages/napcat-onebot/action/example/GuildActionsExamples.ts b/packages/napcat-onebot/action/example/GuildActionsExamples.ts index 895e414b8..2e0a1fad4 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: null, + response: [{ guild_id: '123456', guild_name: '测试频道' }], }, GetGuildProfile: { - payload: {}, - response: null, + payload: { guild_id: '123456' }, + response: { guild_id: '123456', guild_name: '测试频道', guild_display_id: '123' }, }, }; diff --git a/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts b/packages/napcat-onebot/action/extends/ClickInlineKeyboardButton.ts index 1f9ab98ed..f25123b0d 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.Optional(Type.String({ default: '', description: '按钮ID' })), - callback_data: Type.Optional(Type.String({ default: '', description: '回调数据' })), - msg_seq: Type.Optional(Type.String({ default: '10086', description: '消息序列号' })), + button_id: Type.String({ default: '', description: '按钮ID' }), + callback_data: Type.String({ default: '', description: '回调数据' }), + msg_seq: 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 ba94804e9..a478150f9 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' })), - cookie: Type.Optional(Type.String({ default: '', description: '分页Cookie' })), + count: Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' }), + cookie: 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 5148f709b..3bdd5b135 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '聊天类型' })), + chat_type: 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 fd48ffb40..062e9c81e 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.Optional(Type.String({ default: '50', description: '获取数量' })), + count: 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 73007abe2..4806c2f16 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.Optional(Type.Number({ default: 0, description: '数量,0代表全部' })), + count: Type.Number({ default: 0, description: '数量,0代表全部' }), }); type PayloadType = Static; @@ -46,7 +46,6 @@ export class GetEmojiLikes extends OneBotAction { override returnSchema = ReturnSchema; async _handle (payload: PayloadType) { - const count = payload.count!; let peer: Peer; let msgId: string; @@ -67,7 +66,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 = count === 0 ? 200 : Math.ceil(count / 15); + const needFetchCount = payload.count === 0 ? 200 : Math.ceil(payload.count / 15); for (let page = 0; page < needFetchCount; page++) { const res = await this.core.apis.MsgApi.getMsgEmojiLikesList( peer, msg.msgSeq, payload.emoji_id.toString(), emojiType, cookie, 15 @@ -83,8 +82,8 @@ export class GetEmojiLikes extends OneBotAction { cookie = res.cookie; } // 切断多余部分 - if (count > 0) { - emojiLikeList.splice(count); + if (payload.count > 0) { + emojiLikeList.splice(payload.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 b9cf60285..c9eba7e0d 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' })), - count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' })), + start: Type.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' }), + count: Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' }), }); type PayloadType = Static; @@ -61,12 +61,10 @@ 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, +start, +count, type); + const ret = await this.core.apis.UserApi.getProfileLike(userUid ?? this.core.selfInfo.uid, +payload.start, +payload.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 4eead898c..aa7525116 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.Optional(Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' })), + rsp: 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 6a30ccc64..fc9c36e16 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.Optional(Type.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' })), - wording: Type.Optional(Type.String({ default: ' ', description: '状态文字内容' })), + face_type: Type.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' }), + wording: 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 02ae20b60..3e055bea3 100644 --- a/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts +++ b/packages/napcat-onebot/action/extends/SetGroupAlbumMediaLike.ts @@ -7,6 +7,7 @@ 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 bb34e2b3e..f5b9783a0 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.Optional(Type.String({ default: '', description: '专属头衔' })), + special_title: 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 0cc2c8ab0..aef09f5da 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,10 +39,6 @@ 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); @@ -50,8 +46,8 @@ export default class GetFriendMsgHistory extends OneBotAction { @@ -59,7 +55,7 @@ export default class GetFriendMsgHistory extends OneBotAction this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl))) + msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url))) ).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 00796225d..8fc45483d 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' })), + file_count: 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 459fdd442..a5718edac 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.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: '是否反向排序(旧版本兼容)' })), + 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 PayloadType = Static; @@ -37,18 +37,13 @@ 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, +count, reverseOrder)).msgList - : (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList; + ? (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; if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`); // 转换序号 await Promise.all(msgList.map(async msg => { @@ -56,7 +51,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl, quickReply))) + 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 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 600eceb2c..cc20cf5f1 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' })), + file_count: 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 6bf35250d..071e41792 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GetOnlineClient.ts @@ -17,14 +17,16 @@ 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 (): Promise { + async _handle () { + // 注册监听 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 12f211dd1..7610917ec 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.Optional(Type.Union([Type.Boolean(), Type.String()], { default: false, description: '是否不使用缓存' })), + no_cache: 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 8d7afe736..8683e2d6f 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 { + async _handle () { return { level: 1 }; } } diff --git a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts index f863c66a7..82c246977 100644 --- a/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts +++ b/packages/napcat-onebot/action/go-cqhttp/GoCQHTTPGetModelShow.ts @@ -26,12 +26,7 @@ export class GoCQHTTPGetModelShow extends OneBotAction; - -const ReturnSchema = Type.Null(); - -type ReturnType = Static; +import { Type } from '@sinclair/typebox'; +import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples'; // 兼容性代码 -export class GoCQHTTPSetModelShow extends OneBotAction { +export class GoCQHTTPSetModelShow extends OneBotAction { override actionName = ActionName.GoCQHTTP_SetModelShow; - override payloadSchema = PayloadSchema; - override returnSchema = ReturnSchema; + override payloadSchema = Type.Object({}); + override returnSchema = Type.Null(); override actionSummary = '设置机型'; - override actionDescription = '设置当前账号的设备机型名称;当前兼容实现不执行实际切换'; + override actionDescription = '设置当前账号的设备机型名称'; override actionTags = ['Go-CQHTTP']; - override payloadExample = {}; - override returnExample = null; + override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.payload; + override returnExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.response; + + async _handle () { - 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 a636cf646..59de606f3 100644 --- a/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts +++ b/packages/napcat-onebot/action/go-cqhttp/SendForwardMsg.ts @@ -1,34 +1,14 @@ -import type { OB11MessageMixType } from '@/napcat-onebot/types'; -import { - ContextMode, - normalize, - ReturnDataType, - SendMsgBase, - SendMsgPayload, - SendMsgPayloadSchema, -} from '@/napcat-onebot/action/msg/SendMsg'; +import { OB11MessageMixType } from '@/napcat-onebot/types'; +import { ContextMode, normalize, ReturnDataType, SendMsgBase, SendMsgPayload } 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'; -const GoCQHTTPSendForwardPayloadSchema = Type.Intersect([ - Type.Omit(SendMsgPayloadSchema, ['message']), - Type.Object({ - messages: OB11MessageMixTypeSchema, - }), -]); - -type GoCQHTTPSendForwardMsgPayload = Static & { - message?: OB11MessageMixType; -}; +// 未验证 +type GoCQHTTPSendForwardMsgPayload = SendMsgPayload & { messages?: OB11MessageMixType; }; export class GoCQHTTPSendForwardMsgBase extends SendMsgBase { - override payloadSchema = GoCQHTTPSendForwardPayloadSchema; - - protected override getMessageForCheck (payload: SendMsgPayload): OB11MessageMixType { - const forwardPayload = payload as SendMsgPayload & GoCQHTTPSendForwardMsgPayload; - return normalize(forwardPayload.messages); + protected override async check (payload: GoCQHTTPSendForwardMsgPayload) { + if (payload.messages) payload.message = normalize(payload.messages); + return super.check(payload); } } export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase { @@ -44,6 +24,11 @@ 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; @@ -58,18 +43,7 @@ export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase { message_id: 123456, }; - 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 { + override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise { return this.base_handle(payload, ContextMode.Private); } } @@ -87,18 +61,7 @@ export class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase { message_id: 123456, }; - 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 { + override async _handle (payload: GoCQHTTPSendForwardMsgPayload): 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 a16134409..a656a9124 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.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)' })), + 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)' }), }); export type SendGroupNoticePayload = Static; @@ -29,11 +29,6 @@ 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) { // 公告图逻辑 @@ -61,11 +56,11 @@ export class SendGroupNotice extends OneBotAction const publishGroupBulletinResult = await this.core.apis.WebApi.setGroupNotice( payload.group_id.toString(), payload.content, - +pinned, - +type, - +showEditCard, - +tipWindowType, - +confirmRequired, + +payload.pinned, + +payload.type, + +payload.is_show_edit_card, + +payload.tip_window_type, + +payload.confirm_required, 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 cafae0617..b1bcec06d 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.Optional(Type.Boolean({ default: true, description: '是否执行上传' })), + upload_file: 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 04b8a9d66..e664b6889 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.Optional(Type.Boolean({ default: true, description: '是否执行上传' })), + upload_file: 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 855d38443..0188af771 100644 --- a/packages/napcat-onebot/action/group/SendGroupMsg.ts +++ b/packages/napcat-onebot/action/group/SendGroupMsg.ts @@ -15,12 +15,6 @@ 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 2d8b655b6..2f47f1275 100644 --- a/packages/napcat-onebot/action/group/SetGroupAddRequest.ts +++ b/packages/napcat-onebot/action/group/SetGroupAddRequest.ts @@ -31,7 +31,8 @@ export default class SetGroupAddRequest extends OneBotAction { const flag = payload.flag.toString(); const approve = payload.approve?.toString() !== 'false'; - const count = payload.count!; + const reason = payload.reason ?? ' '; + const count = payload.count; const invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(flag); const { doubt, notify } = invite_notify ? { @@ -46,12 +47,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 723e56acf..1e0d714c6 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '禁言时长(秒)' })), + duration: 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 b6dda41bb..b7f0dc010 100644 --- a/packages/napcat-onebot/action/group/SetGroupLeave.ts +++ b/packages/napcat-onebot/action/group/SetGroupLeave.ts @@ -20,21 +20,13 @@ export default class SetGroupLeave extends OneBotAction override payloadSchema = PayloadSchema; override returnSchema = ReturnSchema; override actionSummary = '退出群组'; - override actionDescription = '退出指定群聊;群主可通过 is_dismiss=true 解散群聊'; + override actionDescription = '退出或解散指定群聊'; override actionTags = ['群组接口']; override payloadExample = GroupActionsExamples.SetGroupLeave.payload; override returnExample = GroupActionsExamples.SetGroupLeave.response; async _handle (payload: PayloadType): Promise { - 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()); - } + 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 b78b6ce1e..c15d7f7ea 100644 --- a/packages/napcat-onebot/action/guild/GetGuildList.ts +++ b/packages/napcat-onebot/action/guild/GetGuildList.ts @@ -1,27 +1,20 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; import { ActionName } from '@/napcat-onebot/action/router'; -import { Static, Type } from '@sinclair/typebox'; +import { Type } from '@sinclair/typebox'; +import { GuildActionsExamples } from '../example/GuildActionsExamples'; -const PayloadSchema = Type.Object({}); - -type PayloadType = Static; - -const ReturnSchema = Type.Null(); - -type ReturnType = Static; - -export class GetGuildList extends OneBotAction { +export class GetGuildList extends OneBotAction { override actionName = ActionName.GetGuildList; - override payloadSchema = PayloadSchema; - override returnSchema = ReturnSchema; + override payloadSchema = Type.Object({}); + override returnSchema = Type.Null(); override actionSummary = '获取频道列表'; - override actionDescription = '获取当前帐号已加入的频道列表;当前兼容实现返回空结果'; + override actionDescription = '获取当前帐号已加入的频道列表'; override actionTags = ['频道接口']; - override payloadExample = {}; - override returnExample = null; + override payloadExample = GuildActionsExamples.GetGuildList.payload; + override returnExample = GuildActionsExamples.GetGuildList.response; + + async _handle (): Promise { - async _handle (): Promise { - return null; } } diff --git a/packages/napcat-onebot/action/guild/GetGuildProfile.ts b/packages/napcat-onebot/action/guild/GetGuildProfile.ts index 2f8993120..4985aa9f9 100644 --- a/packages/napcat-onebot/action/guild/GetGuildProfile.ts +++ b/packages/napcat-onebot/action/guild/GetGuildProfile.ts @@ -1,27 +1,20 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; import { ActionName } from '@/napcat-onebot/action/router'; -import { Static, Type } from '@sinclair/typebox'; +import { Type } from '@sinclair/typebox'; +import { GuildActionsExamples } from '../example/GuildActionsExamples'; -const PayloadSchema = Type.Object({}); - -type PayloadType = Static; - -const ReturnSchema = Type.Null(); - -type ReturnType = Static; - -export class GetGuildProfile extends OneBotAction { +export class GetGuildProfile extends OneBotAction { override actionName = ActionName.GetGuildProfile; - override payloadSchema = PayloadSchema; - override returnSchema = ReturnSchema; + override payloadSchema = Type.Object({}); + override returnSchema = Type.Null(); override actionSummary = '获取频道个人信息'; - override actionDescription = '获取当前帐号在频道中的个人资料;当前兼容实现返回空结果'; + override actionDescription = '获取当前帐号在频道中的个人资料'; override actionTags = ['频道接口']; - override payloadExample = {}; - override returnExample = null; + override payloadExample = GuildActionsExamples.GetGuildProfile.payload; + override returnExample = GuildActionsExamples.GetGuildProfile.response; + + async _handle (): Promise { - async _handle (): Promise { - return null; } } diff --git a/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts b/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts index 89ebb3e73..98f99b9d9 100644 --- a/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts +++ b/packages/napcat-onebot/action/msg/MarkMsgAsRead.ts @@ -15,7 +15,6 @@ type PayloadType = Static; const ReturnSchema = Type.Null({ description: '操作结果' }); type ReturnType = Static; -const EmptyPayloadSchema = Type.Object({}); class MarkMsgAsRead extends OneBotAction { override actionSummary = '标记消息已读'; @@ -83,10 +82,8 @@ export class GoCQHTTPMarkMsgAsRead extends MarkMsgAsRead { override actionSummary = '标记消息已读 (Go-CQHTTP)'; } -export class MarkAllMsgAsRead extends OneBotAction, null> { +export class MarkAllMsgAsRead extends OneBotAction { 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 2058bf271..8bbe20b6b 100644 --- a/packages/napcat-onebot/action/msg/SendMsg.ts +++ b/packages/napcat-onebot/action/msg/SendMsg.ts @@ -1,8 +1,6 @@ import { - OB11MessageDataType, -} from '@/napcat-onebot/types'; -import type { OB11MessageData, + OB11MessageDataType, OB11MessageMixType, OB11MessageNode, OB11PostContext, @@ -10,17 +8,16 @@ import type { 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 } from 'napcat-core'; -import type { NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from 'napcat-core'; +import { ChatType, ElementType, 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 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 { PacketMsg } from 'napcat-core/packet/message/message'; +import { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter'; +import { Static, Type } from '@sinclair/typebox'; import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples'; import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message'; -import type { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2'; +import { 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)' })), @@ -52,43 +49,15 @@ 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[] { - const normalized: OB11MessageData[] = typeof message === 'string' + return typeof message === 'string' ? ( autoEscape - ? [{ type: OB11MessageDataType.text, data: { text: message } } as OB11MessageData] + ? [{ type: OB11MessageDataType.text, data: { text: message } }] : decodeCQCode(message) ) : Array.isArray(message) ? message : [message]; - - return normalizeMessageSegments(normalized); } export async function createContext (core: NapCatCore, payload: OB11PostContext | undefined, contextMode: ContextMode = ContextMode.Normal): Promise { @@ -159,26 +128,12 @@ 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: TSchema = SendMsgPayloadSchema; - override returnSchema: TSchema = SendMsgReturnSchema; + override payloadSchema = SendMsgPayloadSchema; + override returnSchema = 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) { @@ -271,8 +226,8 @@ export class SendMsgBase extends OneBotAction { this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!'); break; } - if (!hasNodeReferenceId(node)) { - const OB11Data = normalize(node.data.content); + if (!node.data.id) { + const OB11Data = normalize(node.type === OB11MessageDataType.node ? node.data.content : node); let sendElements: SendMessageElement[]; const subNodeMessages = OB11Data.filter(isNode); @@ -306,7 +261,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 { + } else if (node.data.id) { const id = node.data.id; const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(+id) || MessageUnique.getPeerByMsgId(id); if (!nodeMsg) { @@ -353,6 +308,8 @@ 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) { @@ -413,8 +370,8 @@ export class SendMsgBase extends OneBotAction { }; let nodeMsgIds: string[] = []; for (const messageNode of messageNodes) { - if (hasNodeReferenceId(messageNode)) { - const nodeId = messageNode.data.id; + const nodeId = messageNode.data.id; + if (nodeId) { // 对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 93b521b12..6dfea5122 100644 --- a/packages/napcat-onebot/action/msg/SendPrivateMsg.ts +++ b/packages/napcat-onebot/action/msg/SendPrivateMsg.ts @@ -18,12 +18,6 @@ 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 bbc750e1f..444c97c2e 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.Optional(Type.Number({ default: 50, description: '获取数量' })), + count: Type.Number({ default: 50, description: '获取数量' }), }); export type GetDoubtFriendsAddRequestPayload = Static; @@ -20,6 +20,6 @@ export class GetDoubtFriendsAddRequest extends OneBotAction; @@ -13,10 +16,11 @@ export class SetDoubtFriendsAddRequest extends OneBotAction = T & StreamPacketBasic; +export enum StreamStatus { + Stream = 'stream', // 分片流数据包 + Response = 'response', // 流最终响应 + Reset = 'reset', // 重置流 + Error = 'error', // 流错误 +} 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 deleted file mode 100644 index 25e286615..000000000 --- a/packages/napcat-onebot/action/stream/StreamTypes.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 0c07a8d49..4b788dbc1 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 4d0cdbd70..dd70172a8 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '获取的消息数量' })), + count: 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 efa6638db..c2f15e9e9 100644 --- a/packages/napcat-onebot/action/system/GetVersionInfo.ts +++ b/packages/napcat-onebot/action/system/GetVersionInfo.ts @@ -3,10 +3,6 @@ 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: '协议版本' }), @@ -15,9 +11,8 @@ 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 376c794fc..15da1e1bf 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取的数量' })), + count: 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 e0708a750..869bc919e 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.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '点赞次数' })), + times: 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 68920df22..c4b047ac4 100644 --- a/packages/napcat-onebot/types/message.ts +++ b/packages/napcat-onebot/types/message.ts @@ -276,16 +276,10 @@ export const OB11MessageFlashTransferSchema = Type.Object({ // 但为了与原始类型完全兼容,我们使用 Type.Unknown 来表示递归部分 // 合并转发消息节点 -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({ +export const OB11MessageNodeSchema = 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: '发送者昵称' }), @@ -298,14 +292,9 @@ export const OB11MessageNodeInlineSchema = Type.Object({ }))), summary: Type.Optional(Type.String({ description: '摘要' })), prompt: Type.Optional(Type.String({ 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: '合并转发消息节点' }); + time: Type.Optional(Type.String({ description: '时间' })), + }), +}, { $id: 'OB11MessageNode', description: '合并转发消息节点' }); // 合并转发消息段 export const OB11MessageForwardSchema = Type.Object({ @@ -445,9 +434,7 @@ export type OB11MessageJson = Static; export type OB11MessageXml = Static; export type OB11MessageMarkdown = Static; export type OB11MessageMiniApp = Static; -export type OB11MessageNodeReference = Static; -export type OB11MessageNodeInline = Static; -export type OB11MessageNode = OB11MessageNodeReference | OB11MessageNodeInline; +export type OB11MessageNode = Static; export type OB11MessageForward = Static; export type OB11MessageOnlineFile = Static; export type OB11MessageFlashTransfer = Static; @@ -460,7 +447,7 @@ export type OB11Message = Static; // 合并转发消息节点纯文本接口定义 export type OB11MessageNodePlain = OB11MessageNode & { - data: OB11MessageNode['data'] & { + data: { content?: Array; message: Array; }; diff --git a/packages/napcat-schema/index.ts b/packages/napcat-schema/index.ts index d89522a8a..eb98095cf 100644 --- a/packages/napcat-schema/index.ts +++ b/packages/napcat-schema/index.ts @@ -21,8 +21,6 @@ interface ActionSchemaInfo { tags?: string[]; payloadExample?: unknown; returnExample?: unknown; - supported?: boolean; - unsupportedReason?: string; errorExamples?: Array<{ code: number, description: string; }>; } @@ -492,8 +490,6 @@ export function initSchemas () { tags: action.actionTags, payloadExample: action.payloadExample, returnExample: action.returnExample, - supported: action.supported, - unsupportedReason: action.unsupportedReason, errorExamples: action.errorExamples, }; }); @@ -513,8 +509,6 @@ export function initSchemas () { tags: action.actionTags, payloadExample: action.payloadExample, returnExample: action.returnExample, - supported: action.supported, - unsupportedReason: action.unsupportedReason, errorExamples: action.errorExamples, }; }); @@ -576,23 +570,6 @@ 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) @@ -655,17 +632,13 @@ function appendActionPaths (openapi: Record) { paths[path] = { post: { - 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 || ''), + summary: schemas.summary || actionName, + deprecated: false, + description: schemas.description || '', tags: schemas.tags || [], - 'x-supported': schemas.supported !== false, - ...(schemas.unsupportedReason ? { 'x-unsupported-reason': schemas.unsupportedReason } : {}), parameters: [], requestBody: { - description: schemas.supported === false ? '兼容占位接口参数;当前版本调用将返回业务错误' : 'API 参数', + description: 'API 参数', content: { 'application/json': { schema: cleanPayload, diff --git a/packages/napcat-test/action-contract.test.ts b/packages/napcat-test/action-contract.test.ts deleted file mode 100644 index 116cd1599..000000000 --- a/packages/napcat-test/action-contract.test.ts +++ /dev/null @@ -1,464 +0,0 @@ -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 5f10850f3..9cd9443b9 100644 --- a/packages/napcat-test/schema.test.ts +++ b/packages/napcat-test/schema.test.ts @@ -1,91 +1,12 @@ -import { describe, expect, test, vi } from 'vitest'; +import { describe, expect, test } from 'vitest'; import { TypeCompiler } from '@sinclair/typebox/compiler'; import { Value } from '@sinclair/typebox/value'; import { Type } from '@sinclair/typebox'; -import { OB11MessageDataSchema, OB11MessageNodeSchema, OB11MessageSchema, OB11PostSendMsgSchema } from '../napcat-onebot/types/message'; +import { OB11MessageDataSchema, 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', () => { @@ -142,142 +63,6 @@ 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 f75c9652c..7dc4f8369 100644 --- a/packages/napcat-test/vitest.config.ts +++ b/packages/napcat-test/vitest.config.ts @@ -13,8 +13,6 @@ 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'), }, }, });