fix: 对齐 OneBot schema 与合并转发消息处理行为 (#1694)

* fix: make defaulted request fields optional

* fix: align onebot schemas with runtime behavior

* fix: tighten schema and unsupported action metadata

* fix: reject empty forward reference ids

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

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

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

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

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

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

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

* fix: remove outdated production test checklist for OneBot schema alignment
This commit is contained in:
吴天一 authored and GitHub committed 2026-03-12 01:54:33 +08:00
1 parent 8b2207e109
commit deae7fd467
54 files changed
+1078 -195

No files matched your search

@@ -1,11 +1,12 @@
import { ActionName, BaseCheckResult } from './router';
import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler';
import { Value } from '@sinclair/typebox/value';
import { NapCatCore } from 'napcat-core';
import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index';
import { NetworkAdapterConfig } from '../config/config';
import { TSchema } from '@sinclair/typebox';
import { StreamPacket, StreamPacketBasic, StreamStatus } from './stream/StreamBasic';
import type { NapCatCore } from 'napcat-core';
import type { NapCatOneBot11Adapter } from '@/napcat-onebot/index';
import type { OB11Return } from '@/napcat-onebot/types';
import type { NetworkAdapterConfig } from '../config/config';
import type { TSchema } from '@sinclair/typebox';
import { StreamPacket, StreamPacketBasic, StreamStatus } from './stream/StreamTypes';
export const ActionExamples = {
Common: {
errors: [
@@ -57,6 +58,8 @@ export abstract class OneBotAction<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: { no_cache: false },
payload: {},
response: [],
},
GoCQHTTPCheckUrlSafely: {
@@ -69,11 +69,16 @@ export const GoCQHTTPActionsExamples = {
},
GoCQHTTPGetModelShow: {
payload: { model: 'iPhone 13' },
response: { variants: [] },
response: [{
variants: {
model_show: 'napcat',
need_pay: false,
},
}],
},
GoCQHTTPSetModelShow: {
payload: { model: 'iPhone 13', model_show: 'iPhone 13' },
response: {},
payload: {},
response: null,
},
QuickAction: {
payload: { context: {}, operation: {} },
@@ -1,10 +1,10 @@
export const GuildActionsExamples = {
GetGuildList: {
payload: {},
response: [{ guild_id: '123456', guild_name: '测试频道' }],
response: null,
},
GetGuildProfile: {
payload: { guild_id: '123456' },
response: { guild_id: '123456', guild_name: '测试频道', guild_display_id: '123' },
payload: {},
response: null,
},
};
@@ -5,9 +5,9 @@ import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
bot_appid: Type.String({ description: '机器人AppID' }),
button_id: Type.String({ default: '', description: '按钮ID' }),
callback_data: Type.String({ default: '', description: '回调数据' }),
msg_seq: Type.String({ default: '10086', description: '消息序列号' }),
button_id: Type.Optional(Type.String({ default: '', description: '按钮ID' })),
callback_data: Type.Optional(Type.String({ default: '', description: '回调数据' })),
msg_seq: Type.Optional(Type.String({ default: '10086', description: '消息序列号' })),
});
type PayloadType = Static<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.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
count: Type.Optional(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.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' }),
cookie: Type.String({ default: '', description: '分页Cookie' }),
count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 20, description: '获取数量' })),
cookie: Type.Optional(Type.String({ default: '', description: '分页Cookie' })),
});
type PayloadType = Static<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.Union([Type.Number(), Type.String()], { default: 1, description: '聊天类型' }),
chat_type: Type.Optional(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.String({ default: '50', description: '获取数量' }),
count: Type.Optional(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.Number({ default: 0, description: '数量,0代表全部' }),
count: Type.Optional(Type.Number({ default: 0, description: '数量,0代表全部' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -46,6 +46,7 @@ export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
override returnSchema = ReturnSchema;
async _handle (payload: PayloadType) {
const count = payload.count!;
let peer: Peer;
let msgId: string;
@@ -66,7 +67,7 @@ export class GetEmojiLikes extends OneBotAction<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 = payload.count === 0 ? 200 : Math.ceil(payload.count / 15);
const needFetchCount = count === 0 ? 200 : Math.ceil(count / 15);
for (let page = 0; page < needFetchCount; page++) {
const res = await this.core.apis.MsgApi.getMsgEmojiLikesList(
peer, msg.msgSeq, payload.emoji_id.toString(), emojiType, cookie, 15
@@ -82,8 +83,8 @@ export class GetEmojiLikes extends OneBotAction<PayloadType, ReturnType> {
cookie = res.cookie;
}
// 切断多余部分
if (payload.count > 0) {
emojiLikeList.splice(payload.count);
if (count > 0) {
emojiLikeList.splice(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.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' }),
count: Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' }),
start: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '起始位置' })),
count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 10, description: '获取数量' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -61,10 +61,12 @@ 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, +payload.start, +payload.count, type);
const ret = await this.core.apis.UserApi.getProfileLike(userUid ?? this.core.selfInfo.uid, +start, +count, type);
const data = ret.info.userLikeInfos[0];
if (!data) {
throw new Error('get info error');
@@ -6,7 +6,7 @@ import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({
cmd: Type.String({ description: '命令字' }),
data: Type.String({ description: '十六进制数据' }),
rsp: Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' }),
rsp: Type.Optional(Type.Union([Type.String(), Type.Boolean()], { default: true, description: '是否等待响应' })),
});
type PayloadType = Static<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.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' }),
wording: Type.String({ default: ' ', description: '状态文字内容' }),
face_type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: '1', description: '图标类型' })),
wording: Type.Optional(Type.String({ default: ' ', description: '状态文字内容' })),
});
type PayloadType = Static<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,7 +7,6 @@ const PayloadSchema = Type.Object({
album_id: Type.String({ description: '相册ID' }),
lloc: Type.String({ description: '媒体ID (lloc)' }),
id: Type.String({ description: '点赞ID' }), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
set: Type.Boolean({ default: true, description: '是否点赞' }), // true=点赞 false=取消点赞 未实现
});
type PayloadType = Static<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.String({ default: '', description: '专属头衔' }),
special_title: Type.Optional(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.String({ default: '', description: '手机号' }),
phone_number: Type.Optional(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',
save_path: 'C:\\save',
element_id: '456',
};
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.Number({ default: 20, description: '获取消息数量' }),
reverse_order: Type.Boolean({ default: false, description: '是否反向排序' }),
disable_get_url: Type.Boolean({ default: false, description: '是否禁用获取URL' }),
parse_mult_msg: Type.Boolean({ default: true, description: '是否解析合并消息' }),
quick_reply: Type.Boolean({ default: false, description: '是否快速回复' }),
reverseOrder: Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' }),
count: Type.Optional(Type.Number({ default: 20, description: '获取消息数量' })),
reverse_order: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序' })),
disable_get_url: Type.Optional(Type.Boolean({ default: false, description: '是否禁用获取URL' })),
parse_mult_msg: Type.Optional(Type.Boolean({ default: true, description: '是否解析合并消息' })),
quick_reply: Type.Optional(Type.Boolean({ default: false, description: '是否快速回复' })),
reverseOrder: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -39,6 +39,10 @@ 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);
@@ -46,8 +50,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, +payload.count, payload.reverse_order || payload.reverseOrder)).msgList
: (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +payload.count)).msgList;
? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +count, reverseOrder)).msgList
: (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList;
if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`);
// 转换序号
await Promise.all(msgList.map(async msg => {
@@ -55,7 +59,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, payload.parse_mult_msg, payload.disable_get_url)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl)))
).filter((msg): msg is OB11Message => msg !== undefined);
return { messages: ob11MsgList };
}
@@ -8,7 +8,7 @@ const PayloadSchema = Type.Object({
group_id: Type.String({ description: '群号' }),
folder_id: Type.Optional(Type.String({ description: '文件夹ID' })),
folder: Type.Optional(Type.String({ description: '文件夹ID' })),
file_count: Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' }),
file_count: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' })),
});
type PayloadType = Static<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.Number({ default: 20, description: '获取消息数量' }),
reverse_order: Type.Boolean({ default: false, description: '是否反向排序' }),
disable_get_url: Type.Boolean({ default: false, description: '是否禁用获取URL' }),
parse_mult_msg: Type.Boolean({ default: true, description: '是否解析合并消息' }),
quick_reply: Type.Boolean({ default: false, description: '是否快速回复' }),
reverseOrder: Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' }),
count: Type.Optional(Type.Number({ default: 20, description: '获取消息数量' })),
reverse_order: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序' })),
disable_get_url: Type.Optional(Type.Boolean({ default: false, description: '是否禁用获取URL' })),
parse_mult_msg: Type.Optional(Type.Boolean({ default: true, description: '是否解析合并消息' })),
quick_reply: Type.Optional(Type.Boolean({ default: false, description: '是否快速回复' })),
reverseOrder: Type.Optional(Type.Boolean({ default: false, description: '是否反向排序(旧版本兼容)' })),
});
type PayloadType = Static<typeof PayloadSchema>;
@@ -37,13 +37,18 @@ 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, +payload.count, payload.reverse_order || payload.reverseOrder)).msgList
: (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +payload.count)).msgList;
? (await this.core.apis.MsgApi.getMsgHistory(peer, startMsgId, +count, reverseOrder)).msgList
: (await this.core.apis.MsgApi.getAioFirstViewLatestMsgs(peer, +count)).msgList;
if (msgList.length === 0) throw new Error(`消息${payload.message_seq}不存在`);
// 转换序号
await Promise.all(msgList.map(async msg => {
@@ -51,7 +56,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends OneBotAction<PayloadType
}));
// 烘焙消息
const ob11MsgList = (await Promise.all(
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, payload.parse_mult_msg, payload.disable_get_url, payload.quick_reply)))
msgList.map(msg => this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat, parseMultMsg, disableGetUrl, quickReply)))
).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.Union([Type.Number(), Type.String()], { default: 50, description: '文件数量' }),
file_count: Type.Optional(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,16 +17,14 @@ 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 () {
// 注册监听
async _handle (): Promise<ReturnType> {
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.Union([Type.Boolean(), Type.String()], { default: false, description: '是否不使用缓存' }),
no_cache: Type.Optional(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的安全等级';
override actionDescription = '检查指定URL的安全等级;当前兼容实现固定返回安全等级 1';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPCheckUrlSafely.payload;
override returnExample = GoCQHTTPActionsExamples.GoCQHTTPCheckUrlSafely.response;
async _handle () {
async _handle (): Promise<GoCQHTTPCheckUrlSafelyReturn> {
return { level: 1 };
}
}
@@ -26,7 +26,12 @@ export class GoCQHTTPGetModelShow extends OneBotAction<GoCQHTTPGetModelShowPaylo
override actionDescription = '获取当前账号可用的设备机型显示名称列表';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPGetModelShow.payload;
override returnExample = GoCQHTTPActionsExamples.GoCQHTTPGetModelShow.response;
override returnExample = [{
variants: {
model_show: 'napcat',
need_pay: false,
},
}];
async _handle (payload: GoCQHTTPGetModelShowPayload) {
if (!payload.model) {
@@ -1,20 +1,27 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type } from '@sinclair/typebox';
import { GoCQHTTPActionsExamples } from '../example/GoCQHTTPActionsExamples';
import { Static, Type } from '@sinclair/typebox';
const PayloadSchema = Type.Object({});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Null();
type ReturnType = Static<typeof ReturnSchema>;
// 兼容性代码
export class GoCQHTTPSetModelShow extends OneBotAction<void, void> {
export class GoCQHTTPSetModelShow extends OneBotAction<PayloadType, ReturnType> {
override actionName = ActionName.GoCQHTTP_SetModelShow;
override payloadSchema = Type.Object({});
override returnSchema = Type.Null();
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '设置机型';
override actionDescription = '设置当前账号的设备机型名称';
override actionDescription = '设置当前账号的设备机型名称;当前兼容实现不执行实际切换';
override actionTags = ['Go-CQHTTP'];
override payloadExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.payload;
override returnExample = GoCQHTTPActionsExamples.GoCQHTTPSetModelShow.response;
async _handle () {
override payloadExample = {};
override returnExample = null;
async _handle (): Promise<ReturnType> {
return null;
}
}
@@ -1,14 +1,34 @@
import { OB11MessageMixType } from '@/napcat-onebot/types';
import { ContextMode, normalize, ReturnDataType, SendMsgBase, SendMsgPayload } from '@/napcat-onebot/action/msg/SendMsg';
import type { OB11MessageMixType } from '@/napcat-onebot/types';
import {
ContextMode,
normalize,
ReturnDataType,
SendMsgBase,
SendMsgPayload,
SendMsgPayloadSchema,
} from '@/napcat-onebot/action/msg/SendMsg';
import { ActionName } from '@/napcat-onebot/action/router';
import type { BaseCheckResult } from '@/napcat-onebot/action/router';
import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message';
import { Static, Type } from '@sinclair/typebox';
// 未验证
type GoCQHTTPSendForwardMsgPayload = SendMsgPayload & { messages?: OB11MessageMixType; };
const GoCQHTTPSendForwardPayloadSchema = Type.Intersect([
Type.Omit(SendMsgPayloadSchema, ['message']),
Type.Object({
messages: OB11MessageMixTypeSchema,
}),
]);
type GoCQHTTPSendForwardMsgPayload = Static<typeof GoCQHTTPSendForwardPayloadSchema> & {
message?: OB11MessageMixType;
};
export class GoCQHTTPSendForwardMsgBase extends SendMsgBase {
protected override async check (payload: GoCQHTTPSendForwardMsgPayload) {
if (payload.messages) payload.message = normalize(payload.messages);
return super.check(payload);
override payloadSchema = GoCQHTTPSendForwardPayloadSchema;
protected override getMessageForCheck (payload: SendMsgPayload): OB11MessageMixType {
const forwardPayload = payload as SendMsgPayload & GoCQHTTPSendForwardMsgPayload;
return normalize(forwardPayload.messages);
}
}
export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase {
@@ -24,11 +44,6 @@ export class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase {
override returnExample = {
message_id: 123456,
};
protected override async check (payload: GoCQHTTPSendForwardMsgPayload) {
if (payload.messages) payload.message = normalize(payload.messages);
return super.check(payload);
}
}
export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase {
override actionName = ActionName.GoCQHTTP_SendPrivateForwardMsg;
@@ -43,7 +58,18 @@ export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase {
message_id: 123456,
};
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
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> {
return this.base_handle(payload, ContextMode.Private);
}
}
@@ -61,7 +87,18 @@ export class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase {
message_id: 123456,
};
override async _handle (payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType> {
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> {
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.Union([Type.Number(), Type.String()], { default: 0, description: '是否置顶 (0/1)' }),
type: Type.Union([Type.Number(), Type.String()], { default: 1, description: '类型 (默认为 1)' }),
confirm_required: Type.Union([Type.Number(), Type.String()], { default: 1, description: '是否需要确认 (0/1)' }),
is_show_edit_card: Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否显示修改群名片引导 (0/1)' }),
tip_window_type: Type.Union([Type.Number(), Type.String()], { default: 0, description: '弹窗类型 (默认为 0)' }),
pinned: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否置顶 (0/1)' })),
type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '类型 (默认为 1)' })),
confirm_required: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 1, description: '是否需要确认 (0/1)' })),
is_show_edit_card: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '是否显示修改群名片引导 (0/1)' })),
tip_window_type: Type.Optional(Type.Union([Type.Number(), Type.String()], { default: 0, description: '弹窗类型 (默认为 0)' })),
});
export type SendGroupNoticePayload = Static<typeof SendGroupNoticePayloadSchema>;
@@ -29,6 +29,11 @@ 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) {
// 公告图逻辑
@@ -55,11 +60,11 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
const publishGroupBulletinResult = await this.core.apis.WebApi.setGroupNotice(
payload.group_id.toString(),
payload.content,
+payload.pinned,
+payload.type,
+payload.is_show_edit_card,
+payload.tip_window_type,
+payload.confirm_required,
+pinned,
+type,
+showEditCard,
+tipWindowType,
+confirmRequired,
UploadImage?.id,
UploadImage?.width,
UploadImage?.height
@@ -13,7 +13,7 @@ export const GoCQHTTPUploadGroupFilePayloadSchema = Type.Object({
name: Type.String({ description: '文件名' }),
folder: Type.Optional(Type.String({ description: '父目录 ID' })),
folder_id: Type.Optional(Type.String({ description: '父目录 ID (兼容性字段)' })), // 临时扩展
upload_file: Type.Boolean({ default: true, description: '是否执行上传' }),
upload_file: Type.Optional(Type.Boolean({ default: true, description: '是否执行上传' })),
});
export type GoCQHTTPUploadGroupFilePayload = Static<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.Boolean({ default: true, description: '是否执行上传' }),
upload_file: Type.Optional(Type.Boolean({ default: true, description: '是否执行上传' })),
});
export type GoCQHTTPUploadPrivateFilePayload = Static<typeof GoCQHTTPUploadPrivateFilePayloadSchema>;
@@ -15,6 +15,12 @@ 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,8 +31,7 @@ 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 reason = payload.reason ?? ' ';
const count = payload.count;
const count = payload.count!;
const invite_notify = this.obContext.apis.MsgApi.notifyGroupInvite.get(flag);
const { doubt, notify } = invite_notify
? {
@@ -47,12 +46,12 @@ export default class SetGroupAddRequest extends OneBotAction<PayloadType, Return
doubt,
notify,
approve ? NTGroupRequestOperateTypes.KAGREE : NTGroupRequestOperateTypes.KREFUSE,
reason
payload.reason ?? undefined
);
return null;
}
private async findNotify (flag: string, count: number = 100): Promise<{
private async findNotify (flag: string, count: number): 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.Union([Type.Number(), Type.String()], { default: 0, description: '禁言时长(秒)' }),
duration: Type.Optional(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,13 +20,21 @@ export default class SetGroupLeave extends OneBotAction<PayloadType, ReturnType>
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '退出群组';
override actionDescription = '退出或解散指定群聊';
override actionDescription = '退出指定群聊;群主可通过 is_dismiss=true 解散群聊';
override actionTags = ['群组接口'];
override payloadExample = GroupActionsExamples.SetGroupLeave.payload;
override returnExample = GroupActionsExamples.SetGroupLeave.response;
async _handle (payload: PayloadType): Promise<null> {
await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
const isDismiss = typeof payload.is_dismiss === 'string'
? payload.is_dismiss === 'true'
: !!payload.is_dismiss;
if (isDismiss) {
await this.core.apis.GroupApi.destroyGroup(payload.group_id.toString());
} else {
await this.core.apis.GroupApi.quitGroup(payload.group_id.toString());
}
return null;
}
}
@@ -1,20 +1,27 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type } from '@sinclair/typebox';
import { GuildActionsExamples } from '../example/GuildActionsExamples';
import { Static, Type } from '@sinclair/typebox';
export class GetGuildList extends OneBotAction<void, void> {
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> {
override actionName = ActionName.GetGuildList;
override payloadSchema = Type.Object({});
override returnSchema = Type.Null();
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取频道列表';
override actionDescription = '获取当前帐号已加入的频道列表';
override actionDescription = '获取当前帐号已加入的频道列表;当前兼容实现返回空结果';
override actionTags = ['频道接口'];
override payloadExample = GuildActionsExamples.GetGuildList.payload;
override returnExample = GuildActionsExamples.GetGuildList.response;
async _handle (): Promise<void> {
override payloadExample = {};
override returnExample = null;
async _handle (): Promise<ReturnType> {
return null;
}
}
@@ -1,20 +1,27 @@
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { Type } from '@sinclair/typebox';
import { GuildActionsExamples } from '../example/GuildActionsExamples';
import { Static, Type } from '@sinclair/typebox';
export class GetGuildProfile extends OneBotAction<void, void> {
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> {
override actionName = ActionName.GetGuildProfile;
override payloadSchema = Type.Object({});
override returnSchema = Type.Null();
override payloadSchema = PayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '获取频道个人信息';
override actionDescription = '获取当前帐号在频道中的个人资料';
override actionDescription = '获取当前帐号在频道中的个人资料;当前兼容实现返回空结果';
override actionTags = ['频道接口'];
override payloadExample = GuildActionsExamples.GetGuildProfile.payload;
override returnExample = GuildActionsExamples.GetGuildProfile.response;
async _handle (): Promise<void> {
override payloadExample = {};
override returnExample = null;
async _handle (): Promise<ReturnType> {
return null;
}
}
@@ -15,6 +15,7 @@ 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 = '标记消息已读';
@@ -82,8 +83,10 @@ export class GoCQHTTPMarkMsgAsRead extends MarkMsgAsRead {
override actionSummary = '标记消息已读 (Go-CQHTTP)';
}
export class MarkAllMsgAsRead extends OneBotAction<void, null> {
export class MarkAllMsgAsRead extends OneBotAction<Static<typeof EmptyPayloadSchema>, null> {
override actionName = ActionName._MarkAllMsgAsRead;
override payloadSchema = EmptyPayloadSchema;
override returnSchema = ReturnSchema;
override actionSummary = '标记所有消息已读';
override actionTags = ['消息接口'];
override payloadExample = {};
+60 -17
View File
@@ -1,6 +1,8 @@
import {
OB11MessageData,
OB11MessageDataType,
} from '@/napcat-onebot/types';
import type {
OB11MessageData,
OB11MessageMixType,
OB11MessageNode,
OB11PostContext,
@@ -8,16 +10,17 @@ import {
import { ActionName, BaseCheckResult } from '@/napcat-onebot/action/router';
import { decodeCQCode } from '@/napcat-onebot/helper/cqcode';
import { MessageUnique } from 'napcat-common/src/message-unique';
import { ChatType, ElementType, NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from 'napcat-core';
import { ChatType, ElementType } from 'napcat-core';
import type { NapCatCore, Peer, RawMessage, SendArkElement, SendMessageElement } from 'napcat-core';
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
import { stringifyWithBigInt } from 'napcat-common/src/helper';
import { PacketMsg } from 'napcat-core/packet/message/message';
import { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter';
import { Static, Type } from '@sinclair/typebox';
import type { PacketMsg } from 'napcat-core/packet/message/message';
import type { rawMsgWithSendMsg } from 'napcat-core/packet/message/converter';
import { Static, TSchema, Type } from '@sinclair/typebox';
import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples';
import { OB11MessageMixTypeSchema } from '@/napcat-onebot/types/message';
import { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
import type { UploadForwardMsgParams } from '@/napcat-core/packet/transformer/message/UploadForwardMsgV2';
export const SendMsgPayloadSchema = Type.Object({
message_type: Type.Optional(Type.Union([Type.Literal('private'), Type.Literal('group')], { description: '消息类型 (private/group)' })),
@@ -48,15 +51,43 @@ export enum ContextMode {
Group = 2,
}
function normalizeMessageSegments (messages: OB11MessageData[]): OB11MessageData[] {
return messages.map((message) => {
if (message.type !== OB11MessageDataType.node) {
return message;
}
if ('id' in message.data) {
return {
...message,
data: {
...message.data,
id: message.data.id.toString(),
},
};
}
return {
...message,
data: {
...message.data,
content: normalize((message.data.content ?? []) as OB11MessageMixType),
},
};
});
}
// Normalizes a mixed type (CQCode/a single segment/segment array) into a segment array.
export function normalize (message: OB11MessageMixType, autoEscape = false): OB11MessageData[] {
return typeof message === 'string'
const normalized: OB11MessageData[] = typeof message === 'string'
? (
autoEscape
? [{ type: OB11MessageDataType.text, data: { text: message } }]
? [{ type: OB11MessageDataType.text, data: { text: message } } as OB11MessageData]
: decodeCQCode(message)
)
: Array.isArray(message) ? message : [message];
return normalizeMessageSegments(normalized);
}
export async function createContext (core: NapCatCore, payload: OB11PostContext | undefined, contextMode: ContextMode = ContextMode.Normal): Promise<Peer> {
@@ -127,12 +158,26 @@ function isNode (msg: OB11MessageData): msg is OB11MessageNode {
return msg.type === OB11MessageDataType.node;
}
function hasNodeReferenceId (msg: OB11MessageNode): msg is OB11MessageNode & { data: { id: string; }; } {
return 'id' in msg.data && typeof msg.data.id === 'string' && msg.data.id.length > 0;
}
export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
override payloadSchema = SendMsgPayloadSchema;
override returnSchema = SendMsgReturnSchema;
override payloadSchema: TSchema = SendMsgPayloadSchema;
override returnSchema: TSchema = SendMsgReturnSchema;
override actionTags = ['消息接口'];
protected getMessageForCheck (payload: SendMsgPayload): OB11MessageMixType {
return payload.message;
}
protected override async check (payload: SendMsgPayload): Promise<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) {
@@ -225,8 +270,8 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
this.core.context.logger.logWarn('转发消息深度超过3层,将停止解析!');
break;
}
if (!node.data.id) {
const OB11Data = normalize(node.type === OB11MessageDataType.node ? node.data.content : node);
if (!hasNodeReferenceId(node)) {
const OB11Data = normalize(node.data.content);
let sendElements: SendMessageElement[];
const subNodeMessages = OB11Data.filter(isNode);
@@ -260,7 +305,7 @@ export class SendMsgBase extends OneBotAction<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 if (node.data.id) {
} else {
const id = node.data.id;
const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(+id) || MessageUnique.getPeerByMsgId(id);
if (!nodeMsg) {
@@ -307,8 +352,6 @@ export class SendMsgBase extends OneBotAction<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) {
@@ -369,8 +412,8 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
};
let nodeMsgIds: string[] = [];
for (const messageNode of messageNodes) {
const nodeId = messageNode.data.id;
if (nodeId) {
if (hasNodeReferenceId(messageNode)) {
const nodeId = messageNode.data.id;
// 对Msgid和OB11ID混用情况兜底
const nodeMsg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(nodeId)) || MessageUnique.getPeerByMsgId(nodeId);
if (!nodeMsg) {
@@ -18,6 +18,12 @@ 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.Number({ default: 50, description: '获取数量' }),
count: Type.Optional(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,9 +4,6 @@ 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>;
@@ -16,11 +13,10 @@ 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,16 +1,10 @@
import { OneBotAction, OneBotRequestToolkit } from '../OneBotAction';
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
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', // 流错误
}
import { StreamPacket } from './StreamTypes';
export type { StreamPacketBasic, StreamPacket } from './StreamTypes';
export { StreamStatus } from './StreamTypes';
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>>;
}
@@ -0,0 +1,13 @@
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 = {
url: 'http://example.com/file',
error: false,
};
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.Number({ default: 5 * 60 * 1000, description: '文件保留时间 (毫秒)' }), // 默认5分钟 回收 不设置或0为不回收
file_retention: Type.Optional(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.Union([Type.Number(), Type.String()], { default: 50, description: '获取的消息数量' }),
count: Type.Optional(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,6 +3,10 @@ import { ActionName } from '@/napcat-onebot/action/router';
import { napCatVersion } from 'napcat-common/src/version';
import { Type, Static } from '@sinclair/typebox';
const PayloadSchema = Type.Object({});
type PayloadType = Static<typeof PayloadSchema>;
const ReturnSchema = Type.Object({
app_name: Type.String({ description: '应用名称' }),
protocol_version: Type.String({ description: '协议版本' }),
@@ -11,8 +15,9 @@ const ReturnSchema = Type.Object({
type ReturnType = Static<typeof ReturnSchema>;
export default class GetVersionInfo extends OneBotAction<void, ReturnType> {
export default class GetVersionInfo extends OneBotAction<PayloadType, 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.Union([Type.Number(), Type.String()], { default: 10, description: '获取的数量' }),
count: Type.Optional(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.Union([Type.Number(), Type.String()], { default: 1, description: '点赞次数' }),
times: Type.Optional(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}`);
}