Revert "fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)" (#1701)
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
Release NapCat / validate-version (push) Canceled after 0s
Release NapCat / Build-Framework (push) Canceled after 0s
Release NapCat / Build-Shell (push) Canceled after 0s
Release NapCat / Download-QNX64 (push) Canceled after 0s
Release NapCat / release-napcat (push) Canceled after 0s
This reverts commit deae7fd467.
This commit is contained in:
54 files changed
+195
-1078
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<PayloadType, ReturnDataType> {
|
||||
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) {
|
||||
|
||||
@@ -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: {} },
|
||||
|
||||
@@ -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' },
|
||||
},
|
||||
};
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -35,11 +35,11 @@ export class ClickInlineKeyboardButton extends OneBotAction<PayloadType, ReturnT
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
return await this.core.apis.MsgApi.clickInlineKeyboardButton({
|
||||
buttonId: payload.button_id!,
|
||||
buttonId: payload.button_id,
|
||||
peerId: payload.group_id.toString(),
|
||||
botAppid: payload.bot_appid,
|
||||
msgSeq: payload.msg_seq!,
|
||||
callback_data: payload.callback_data!,
|
||||
msgSeq: payload.msg_seq,
|
||||
callback_data: payload.callback_data,
|
||||
dmFlag: 0,
|
||||
chatType: 2,
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' })),
|
||||
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
@@ -27,7 +27,7 @@ export class FetchCustomFace extends OneBotAction<PayloadType, ReturnType> {
|
||||
];
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -64,7 +64,7 @@ export class FetchEmojiLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -77,6 +77,6 @@ export class GetCollectionList extends OneBotAction<PayloadType, ReturnType> {
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
@@ -46,7 +46,6 @@ export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
|
||||
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<PayloadType, ReturnType> {
|
||||
const emojiType = payload.emoji_type ?? (payload.emoji_id.length > 3 ? '2' : '1');
|
||||
const emojiLikeList: Array<{ user_id: string; nick_name: string; }> = [];
|
||||
let cookie = '';
|
||||
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<PayloadType, ReturnType> {
|
||||
cookie = res.cookie;
|
||||
}
|
||||
// 切断多余部分
|
||||
if (count > 0) {
|
||||
emojiLikeList.splice(count);
|
||||
if (payload.count > 0) {
|
||||
emojiLikeList.splice(payload.count);
|
||||
}
|
||||
return { emoji_like_list: emojiLikeList };
|
||||
}
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -61,12 +61,10 @@ export class GetProfileLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
};
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
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');
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -30,8 +30,8 @@ export class SetDiyOnlineStatus extends OneBotAction<PayloadType, ReturnType> {
|
||||
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('设置在线状态失败');
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -29,6 +29,6 @@ export class SetSpecialTitle extends GetPacketStatusDepends<PayloadType, ReturnT
|
||||
async _handle (payload: PayloadType) {
|
||||
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
|
||||
if (!uid) throw new Error('User not found');
|
||||
await this.core.apis.PacketApi.pkt.operation.SetGroupSpecialTitle(+payload.group_id, uid, payload.special_title!);
|
||||
await this.core.apis.PacketApi.pkt.operation.SetGroupSpecialTitle(+payload.group_id, uid, payload.special_title);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
const PayloadSchema = Type.Object({
|
||||
user_id: Type.Optional(Type.String({ description: 'QQ号' })),
|
||||
group_id: Type.Optional(Type.String({ description: '群号' })),
|
||||
phone_number: Type.Optional(Type.String({ default: '', description: '手机号' })),
|
||||
phone_number: Type.String({ default: '', description: '手机号' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
@@ -20,7 +20,7 @@ export class ReceiveOnlineFile extends OneBotAction<ReceiveOnlineFilePayload, an
|
||||
override payloadExample = {
|
||||
user_id: '123456789',
|
||||
msg_id: '123',
|
||||
element_id: '456',
|
||||
save_path: 'C:\\save',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
@@ -11,12 +11,12 @@ import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
|
||||
const PayloadSchema = Type.Object({
|
||||
user_id: Type.String({ description: '用户QQ' }),
|
||||
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<typeof PayloadSchema>;
|
||||
@@ -39,10 +39,6 @@ export default class GetFriendMsgHistory extends OneBotAction<PayloadType, Retur
|
||||
|
||||
async _handle (payload: PayloadType, _adapter: string, config: NetworkAdapterConfig): Promise<ReturnType> {
|
||||
// 处理参数
|
||||
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<PayloadType, Retur
|
||||
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 => {
|
||||
@@ -59,7 +55,7 @@ export default class GetFriendMsgHistory extends OneBotAction<PayloadType, Retur
|
||||
}));
|
||||
// 烘焙消息
|
||||
const ob11MsgList = (await Promise.all(
|
||||
msgList.map(msg => 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 };
|
||||
}
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -33,7 +33,7 @@ export class GetGroupFilesByFolder extends OneBotAction<PayloadType, ReturnType>
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
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,
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -37,18 +37,13 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<PayloadType
|
||||
override returnExample = GoCQHTTPActionsExamples.GetGroupMsgHistory.response;
|
||||
|
||||
async _handle (payload: PayloadType, _adapter: string, config: NetworkAdapterConfig): Promise<ReturnType> {
|
||||
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<PayloadType
|
||||
}));
|
||||
// 烘焙消息
|
||||
const ob11MsgList = (await Promise.all(
|
||||
msgList.map(msg => 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 };
|
||||
}
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -31,7 +31,7 @@ export class GetGroupRootFiles extends OneBotAction<PayloadType, ReturnType> {
|
||||
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,
|
||||
|
||||
@@ -17,14 +17,16 @@ export class GetOnlineClient extends OneBotAction<PayloadType, ReturnType> {
|
||||
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<ReturnType> {
|
||||
async _handle () {
|
||||
// 注册监听
|
||||
this.core.apis.SystemApi.getOnlineDev();
|
||||
await sleep(500);
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
@@ -20,12 +20,12 @@ export class GoCQHTTPCheckUrlSafely extends OneBotAction<GoCQHTTPCheckUrlSafelyP
|
||||
override payloadSchema = GoCQHTTPCheckUrlSafelyPayloadSchema;
|
||||
override returnSchema = GoCQHTTPCheckUrlSafelyReturnSchema;
|
||||
override actionSummary = '检查URL安全性';
|
||||
override actionDescription = '检查指定URL的安全等级;当前兼容实现固定返回安全等级 1';
|
||||
override actionDescription = '检查指定URL的安全等级';
|
||||
override actionTags = ['Go-CQHTTP'];
|
||||
override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPCheckUrlSafely.payload;
|
||||
override returnExample = GoCQHTTPActionsExamples.GoCQHTTPCheckUrlSafely.response;
|
||||
|
||||
async _handle (): Promise<GoCQHTTPCheckUrlSafelyReturn> {
|
||||
async _handle () {
|
||||
return { level: 1 };
|
||||
}
|
||||
}
|
||||
@@ -26,12 +26,7 @@ export class GoCQHTTPGetModelShow extends OneBotAction<GoCQHTTPGetModelShowPaylo
|
||||
override actionDescription = '获取当前账号可用的设备机型显示名称列表';
|
||||
override actionTags = ['Go-CQHTTP'];
|
||||
override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPGetModelShow.payload;
|
||||
override returnExample = [{
|
||||
variants: {
|
||||
model_show: 'napcat',
|
||||
need_pay: false,
|
||||
},
|
||||
}];
|
||||
override returnExample = GoCQHTTPActionsExamples.GoCQHTTPGetModelShow.response;
|
||||
|
||||
async _handle (payload: GoCQHTTPGetModelShowPayload) {
|
||||
if (!payload.model) {
|
||||
|
||||
@@ -1,27 +1,20 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
const PayloadSchema = Type.Object({});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null();
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
|
||||
|
||||
// 兼容性代码
|
||||
export class GoCQHTTPSetModelShow extends OneBotAction<PayloadType, ReturnType> {
|
||||
export class GoCQHTTPSetModelShow extends OneBotAction<void, void> {
|
||||
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<ReturnType> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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<typeof GoCQHTTPSendForwardPayloadSchema> & {
|
||||
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<BaseCheckResult> {
|
||||
payload.message_type = 'private';
|
||||
if (!payload.user_id) {
|
||||
return {
|
||||
valid: false,
|
||||
message: '缺少参数 user_id',
|
||||
};
|
||||
}
|
||||
return super.check(payload);
|
||||
}
|
||||
|
||||
override async _handle (payload: SendMsgPayload): Promise<ReturnDataType> {
|
||||
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
|
||||
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<BaseCheckResult> {
|
||||
payload.message_type = 'group';
|
||||
if (!payload.group_id) {
|
||||
return {
|
||||
valid: false,
|
||||
message: '缺少参数 group_id',
|
||||
};
|
||||
}
|
||||
return super.check(payload);
|
||||
}
|
||||
|
||||
override async _handle (payload: SendMsgPayload): Promise<ReturnDataType> {
|
||||
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
|
||||
return this.base_handle(payload, ContextMode.Group);
|
||||
}
|
||||
}
|
||||
@@ -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<typeof SendGroupNoticePayloadSchema>;
|
||||
@@ -29,11 +29,6 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
|
||||
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<SendGroupNoticePayload, void>
|
||||
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
|
||||
|
||||
@@ -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<typeof GoCQHTTPUploadGroupFilePayloadSchema>;
|
||||
|
||||
@@ -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<typeof GoCQHTTPUploadPrivateFilePayloadSchema>;
|
||||
|
||||
@@ -15,12 +15,6 @@ class SendGroupMsg extends SendMsgBase {
|
||||
protected override async check (payload: SendMsgPayload): Promise<BaseCheckResult> {
|
||||
delete payload.user_id;
|
||||
payload.message_type = 'group';
|
||||
if (!payload.group_id) {
|
||||
return {
|
||||
valid: false,
|
||||
message: '缺少参数 group_id',
|
||||
};
|
||||
}
|
||||
return super.check(payload);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,8 @@ export default class SetGroupAddRequest extends OneBotAction<PayloadType, Return
|
||||
async _handle (payload: PayloadType): Promise<null> {
|
||||
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<PayloadType, Return
|
||||
doubt,
|
||||
notify,
|
||||
approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
|
||||
payload.reason ?? undefined
|
||||
reason
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
private async findNotify (flag: string, count: number): Promise<{
|
||||
private async findNotify (flag: string, count: number = 100): Promise<{
|
||||
doubt: boolean,
|
||||
notify: GroupNotify | undefined;
|
||||
}> {
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
@@ -33,7 +33,7 @@ export default class SetGroupBan extends OneBotAction<PayloadType, ReturnType> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -20,21 +20,13 @@ export default class SetGroupLeave extends OneBotAction<PayloadType, ReturnType>
|
||||
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<null> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null();
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGuildList extends OneBotAction<PayloadType, ReturnType> {
|
||||
export class GetGuildList extends OneBotAction<void, void> {
|
||||
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<void> {
|
||||
|
||||
async _handle (): Promise<ReturnType> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Null();
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGuildProfile extends OneBotAction<PayloadType, ReturnType> {
|
||||
export class GetGuildProfile extends OneBotAction<void, void> {
|
||||
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<void> {
|
||||
|
||||
async _handle (): Promise<ReturnType> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ type PayloadType = Static<typeof PayloadSchema>;
|
||||
const ReturnSchema = Type.Null({ description: '操作结果' });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
const EmptyPayloadSchema = Type.Object({});
|
||||
|
||||
class MarkMsgAsRead extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionSummary = '标记消息已读';
|
||||
@@ -83,10 +82,8 @@ export class GoCQHTTPMarkMsgAsRead extends MarkMsgAsRead {
|
||||
override actionSummary = '标记消息已读 (Go-CQHTTP)';
|
||||
}
|
||||
|
||||
export class MarkAllMsgAsRead extends OneBotAction<Static<typeof EmptyPayloadSchema>, null> {
|
||||
export class MarkAllMsgAsRead extends OneBotAction<void, null> {
|
||||
override actionName = ActionName._MarkAllMsgAsRead;
|
||||
override payloadSchema = EmptyPayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '标记所有消息已读';
|
||||
override actionTags = ['消息接口'];
|
||||
override payloadExample = {};
|
||||
|
||||
@@ -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<Peer> {
|
||||
@@ -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<SendMsgPayload, ReturnDataType> {
|
||||
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<BaseCheckResult> {
|
||||
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<SendMsgPayload, ReturnDataType> {
|
||||
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<SendMsgPayload, ReturnDataType> {
|
||||
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<SendMsgPayload, ReturnDataType> {
|
||||
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<SendMsgPayload, ReturnDataType> {
|
||||
};
|
||||
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) {
|
||||
|
||||
@@ -18,12 +18,6 @@ class SendPrivateMsg extends SendMsgBase {
|
||||
|
||||
protected override async check (payload: SendMsgPayload): Promise<BaseCheckResult> {
|
||||
payload.message_type = 'private';
|
||||
if (!payload.user_id) {
|
||||
return {
|
||||
valid: false,
|
||||
message: '缺少参数 user_id',
|
||||
};
|
||||
}
|
||||
return super.check(payload);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<typeof GetDoubtFriendsAddRequestPayloadSchema>;
|
||||
@@ -20,6 +20,6 @@ export class GetDoubtFriendsAddRequest extends OneBotAction<GetDoubtFriendsAddRe
|
||||
override returnExample = NewActionsExamples.GetDoubtFriendsAddRequest.response;
|
||||
|
||||
async _handle (payload: GetDoubtFriendsAddRequestPayload) {
|
||||
return await this.core.apis.FriendApi.getDoubtFriendRequest(payload.count!);
|
||||
return await this.core.apis.FriendApi.getDoubtFriendRequest(payload.count);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
export const SetDoubtFriendsAddRequestPayloadSchema = Type.Object({
|
||||
flag: Type.String({ description: '请求 flag' }),
|
||||
// 注意强制String 非isNumeric 不遵守则不符合设计
|
||||
approve: Type.Boolean({ default: true, description: '是否同意 (强制为 true)' }),
|
||||
// 该字段没有语义 仅做保留 强制为True
|
||||
});
|
||||
|
||||
export type SetDoubtFriendsAddRequestPayload = Static<typeof SetDoubtFriendsAddRequestPayloadSchema>;
|
||||
@@ -13,10 +16,11 @@ export class SetDoubtFriendsAddRequest extends OneBotAction<SetDoubtFriendsAddRe
|
||||
override payloadSchema = SetDoubtFriendsAddRequestPayloadSchema;
|
||||
override returnSchema = Type.Any();
|
||||
override actionSummary = '处理可疑好友申请';
|
||||
override actionDescription = '同意并处理系统的可疑好友申请';
|
||||
override actionDescription = '同意或拒绝系统的可疑好友申请';
|
||||
override actionTags = ['系统接口'];
|
||||
override payloadExample = {
|
||||
flag: '12345',
|
||||
approve: true,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { OneBotAction, OneBotRequestToolkit } from '../OneBotAction';
|
||||
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
|
||||
import { StreamPacket } from './StreamTypes';
|
||||
|
||||
export type { StreamPacketBasic, StreamPacket } from './StreamTypes';
|
||||
export { StreamStatus } from './StreamTypes';
|
||||
|
||||
export type StreamPacketBasic = {
|
||||
type: StreamStatus;
|
||||
data_type?: string;
|
||||
};
|
||||
export type StreamPacket<T> = T & StreamPacketBasic;
|
||||
export enum StreamStatus {
|
||||
Stream = 'stream', // 分片流数据包
|
||||
Response = 'response', // 流最终响应
|
||||
Reset = 'reset', // 重置流
|
||||
Error = 'error', // 流错误
|
||||
}
|
||||
export abstract class BasicStream<T, R> extends OneBotAction<T, StreamPacket<R>> {
|
||||
abstract override _handle (_payload: T, _adaptername: string, _config: NetworkAdapterConfig, req: OneBotRequestToolkit): Promise<StreamPacket<R>>;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
export type StreamPacketBasic = {
|
||||
type: StreamStatus;
|
||||
data_type?: string;
|
||||
};
|
||||
|
||||
export type StreamPacket<T> = T & StreamPacketBasic;
|
||||
|
||||
export enum StreamStatus {
|
||||
Stream = 'stream', // 分片流数据包
|
||||
Response = 'response', // 流最终响应
|
||||
Reset = 'reset', // 重置流
|
||||
Error = 'error', // 流错误
|
||||
}
|
||||
@@ -15,7 +15,7 @@ export class TestDownloadStream extends OneBotAction<TestDownloadStreamPayload,
|
||||
override actionSummary = '测试下载流';
|
||||
override actionTags = ['流式传输扩展'];
|
||||
override payloadExample = {
|
||||
error: false,
|
||||
url: 'http://example.com/file',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
|
||||
@@ -27,7 +27,7 @@ export const UploadFileStreamPayloadSchema = Type.Object({
|
||||
filename: Type.Optional(Type.String({ description: '文件名' })),
|
||||
reset: Type.Optional(Type.Boolean({ description: '是否重置' })),
|
||||
verify_only: Type.Optional(Type.Boolean({ description: '是否仅验证' })),
|
||||
file_retention: Type.Optional(Type.Number({ default: 5 * 60 * 1000, description: '文件保留时间 (毫秒)' })), // 默认5分钟 回收 不设置或0为不回收
|
||||
file_retention: Type.Number({ default: 5 * 60 * 1000, description: '文件保留时间 (毫秒)' }), // 默认5分钟 回收 不设置或0为不回收
|
||||
});
|
||||
|
||||
export type UploadFileStreamPayload = Static<typeof UploadFileStreamPayloadSchema>;
|
||||
|
||||
@@ -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<typeof GetGroupSystemMsgPayloadSchema>;
|
||||
@@ -36,7 +36,7 @@ export class GetGroupSystemMsg extends OneBotAction<GetGroupSystemMsgPayload, Ge
|
||||
};
|
||||
|
||||
async _handle (params: GetGroupSystemMsgPayload): Promise<GetGroupSystemMsgReturn> {
|
||||
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) => {
|
||||
|
||||
@@ -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<typeof PayloadSchema>;
|
||||
|
||||
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<typeof ReturnSchema>;
|
||||
|
||||
export default class GetVersionInfo extends OneBotAction<PayloadType, ReturnType> {
|
||||
export default class GetVersionInfo extends OneBotAction<void, ReturnType> {
|
||||
override actionName = ActionName.GetVersionInfo;
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
override actionSummary = '获取版本信息';
|
||||
override actionDescription = '获取版本信息';
|
||||
|
||||
@@ -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<typeof GetRecentContactPayloadSchema>;
|
||||
@@ -45,7 +45,7 @@ export default class GetRecentContact extends OneBotAction<GetRecentContactPaylo
|
||||
];
|
||||
|
||||
async _handle (payload: GetRecentContactPayload, _adapter: string, config: NetworkAdapterConfig): Promise<GetRecentContactReturn> {
|
||||
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]);
|
||||
|
||||
@@ -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<typeof SendLikePayloadSchema>;
|
||||
@@ -28,7 +28,7 @@ export default class SendLike extends OneBotAction<SendLikePayload, void> {
|
||||
async _handle (payload: SendLikePayload): Promise<void> {
|
||||
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}`);
|
||||
}
|
||||
|
||||
@@ -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<typeof OB11MessageJsonSchema>;
|
||||
export type OB11MessageXml = Static<typeof OB11MessageXmlSchema>;
|
||||
export type OB11MessageMarkdown = Static<typeof OB11MessageMarkdownSchema>;
|
||||
export type OB11MessageMiniApp = Static<typeof OB11MessageMiniAppSchema>;
|
||||
export type OB11MessageNodeReference = Static<typeof OB11MessageNodeReferenceSchema>;
|
||||
export type OB11MessageNodeInline = Static<typeof OB11MessageNodeInlineSchema>;
|
||||
export type OB11MessageNode = OB11MessageNodeReference | OB11MessageNodeInline;
|
||||
export type OB11MessageNode = Static<typeof OB11MessageNodeSchema>;
|
||||
export type OB11MessageForward = Static<typeof OB11MessageForwardSchema>;
|
||||
export type OB11MessageOnlineFile = Static<typeof OB11MessageOnlineFileSchema>;
|
||||
export type OB11MessageFlashTransfer = Static<typeof OB11MessageFlashTransferSchema>;
|
||||
@@ -460,7 +447,7 @@ export type OB11Message = Static<typeof OB11MessageSchema>;
|
||||
|
||||
// 合并转发消息节点纯文本接口定义
|
||||
export type OB11MessageNodePlain = OB11MessageNode & {
|
||||
data: OB11MessageNode['data'] & {
|
||||
data: {
|
||||
content?: Array<OB11MessageData>;
|
||||
message: Array<OB11MessageData>;
|
||||
};
|
||||
|
||||
@@ -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<string, unknown> {
|
||||
}
|
||||
|
||||
function buildResponseExamples (schemas: ActionSchemaInfo): Record<string, unknown> {
|
||||
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<string, any> = {
|
||||
Success: isMeaninglessSuccessExampleData(successData)
|
||||
@@ -655,17 +632,13 @@ function appendActionPaths (openapi: Record<string, unknown>) {
|
||||
|
||||
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,
|
||||
|
||||
@@ -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<string, unknown> = {}) {
|
||||
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<typeof DefaultedActionPayloadSchema>;
|
||||
|
||||
class DefaultedPayloadAction extends OneBotAction<DefaultedActionPayload, DefaultedActionPayload> {
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {};
|
||||
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {
|
||||
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<string, unknown> = {
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>,
|
||||
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<T> (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', () => {
|
||||
|
||||
@@ -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'),
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user