refactor: rename all coreContext -> core

This commit is contained in:
Wesley F. Young
2024-08-26 09:19:50 +08:00
parent 542c5beb1b
commit b1a1fdbeee
79 changed files with 386 additions and 389 deletions

View File

@@ -4,13 +4,13 @@ import type { NapCatCore } from '@/core';
export abstract class ConfigBase<T> { export abstract class ConfigBase<T> {
name: string; name: string;
coreContext: NapCatCore; core: NapCatCore;
configPath: string; configPath: string;
configData: T = {} as T; configData: T = {} as T;
protected constructor(name: string, coreContext: NapCatCore, configPath: string) { protected constructor(name: string, core: NapCatCore, configPath: string) {
this.name = name; this.name = name;
this.coreContext = coreContext; this.core = core;
this.configPath = configPath; this.configPath = configPath;
fs.mkdirSync(this.configPath, { recursive: true }); fs.mkdirSync(this.configPath, { recursive: true });
this.read(); this.read();
@@ -28,8 +28,8 @@ export abstract class ConfigBase<T> {
} }
read(): T { read(): T {
const logger = this.coreContext.context.logger; const logger = this.core.context.logger;
const configPath = this.getConfigPath(this.coreContext.selfInfo.uin); const configPath = this.getConfigPath(this.core.selfInfo.uin);
if (!fs.existsSync(configPath)) { if (!fs.existsSync(configPath)) {
try { try {
fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8')); fs.writeFileSync(configPath, fs.readFileSync(this.getConfigPath(undefined), 'utf-8'));
@@ -54,8 +54,8 @@ export abstract class ConfigBase<T> {
save(newConfigData: T = this.configData) { save(newConfigData: T = this.configData) {
const logger = this.coreContext.context.logger; const logger = this.core.context.logger;
const selfInfo = this.coreContext.selfInfo; const selfInfo = this.core.selfInfo;
this.configData = newConfigData; this.configData = newConfigData;
const configPath = this.getConfigPath(selfInfo.uin); const configPath = this.getConfigPath(selfInfo.uin);
try { try {

View File

@@ -7,7 +7,7 @@ export type NapCatConfig = typeof napCatDefaultConfig;
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging // eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export class NapCatConfigLoader extends ConfigBase<NapCatConfig> { export class NapCatConfigLoader extends ConfigBase<NapCatConfig> {
constructor(coreContext: NapCatCore, configPath: string) { constructor(core: NapCatCore, configPath: string) {
super('napcat', coreContext, configPath); super('napcat', core, configPath);
} }
} }

View File

@@ -8,19 +8,19 @@ import { NapCatOneBot11Adapter } from '@/onebot';
abstract class BaseAction<PayloadType, ReturnDataType> { abstract class BaseAction<PayloadType, ReturnDataType> {
actionName: ActionName = ActionName.Unknown; actionName: ActionName = ActionName.Unknown;
CoreContext: NapCatCore; core: NapCatCore;
private validate: undefined | ValidateFunction<any> = undefined; private validate: undefined | ValidateFunction<any> = undefined;
PayloadSchema: any = undefined; payloadSchema: any = undefined;
OneBotContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
constructor(onebotContext: NapCatOneBot11Adapter, coreContext: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.OneBotContext = onebotContext; this.obContext = obContext;
this.CoreContext = coreContext; this.core = core;
} }
protected async check(payload: PayloadType): Promise<BaseCheckResult> { protected async check(payload: PayloadType): Promise<BaseCheckResult> {
if (this.PayloadSchema) { if (this.payloadSchema) {
this.validate = new Ajv({ allowUnionTypes: true }).compile(this.PayloadSchema); this.validate = new Ajv({ allowUnionTypes: true }).compile(this.payloadSchema);
} }
if (this.validate && !this.validate(payload)) { if (this.validate && !this.validate(payload)) {
const errors = this.validate.errors as ErrorObject[]; const errors = this.validate.errors as ErrorObject[];
@@ -46,7 +46,7 @@ abstract class BaseAction<PayloadType, ReturnDataType> {
const resData = await this._handle(payload); const resData = await this._handle(payload);
return OB11Response.ok(resData); return OB11Response.ok(resData);
} catch (e: any) { } catch (e: any) {
this.CoreContext.context.logger.logError('发生错误', e); this.core.context.logger.logError('发生错误', e);
return OB11Response.error(e?.toString() || e?.stack?.toString() || '未知错误,可能操作超时', 200); return OB11Response.error(e?.toString() || e?.stack?.toString() || '未知错误,可能操作超时', 200);
} }
} }
@@ -60,7 +60,7 @@ abstract class BaseAction<PayloadType, ReturnDataType> {
const resData = await this._handle(payload); const resData = await this._handle(payload);
return OB11Response.ok(resData, echo); return OB11Response.ok(resData, echo);
} catch (e: any) { } catch (e: any) {
this.CoreContext.context.logger.logError('发生错误', e); this.core.context.logger.logError('发生错误', e);
return OB11Response.error(e.stack?.toString() || e.toString(), 1200, echo); return OB11Response.error(e.stack?.toString() || e.toString(), 1200, echo);
} }
} }

View File

@@ -15,13 +15,13 @@ type Payload = FromSchema<typeof SchemaData>;
export class CreateCollection extends BaseAction<Payload, any> { export class CreateCollection extends BaseAction<Payload, any> {
actionName = ActionName.CreateCollection; actionName = ActionName.CreateCollection;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
return await this.CoreContext.apis.CollectionApi.createCollection( return await this.core.apis.CollectionApi.createCollection(
this.CoreContext.selfInfo.uin, this.core.selfInfo.uin,
this.CoreContext.selfInfo.uid, this.core.selfInfo.uid,
this.CoreContext.selfInfo.nick, this.core.selfInfo.nick,
payload.brief, payload.rawData, payload.brief, payload.rawData,
); );
} }

View File

@@ -13,11 +13,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class FetchCustomFace extends BaseAction<Payload, string[]> { export class FetchCustomFace extends BaseAction<Payload, string[]> {
actionName = ActionName.FetchCustomFace; actionName = ActionName.FetchCustomFace;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
//48 可能正好是QQ需要的一个页面的数量 Tagged Mlikiowa //48 可能正好是QQ需要的一个页面的数量 Tagged Mlikiowa
const ret = await this.CoreContext.apis.MsgApi.fetchFavEmojiList(+(payload.count ?? 48)); const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+(payload.count ?? 48));
return ret.emojiInfoList.map(e => e.url); return ret.emojiInfoList.map(e => e.url);
} }
} }

View File

@@ -21,9 +21,9 @@ type Payload = FromSchema<typeof SchemaData>;
export class FetchEmojiLike extends BaseAction<Payload, any> { export class FetchEmojiLike extends BaseAction<Payload, any> {
actionName = ActionName.FetchEmojiLike; actionName = ActionName.FetchEmojiLike;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msgIdPeer = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msgIdPeer) throw new Error('消息不存在'); if (!msgIdPeer) throw new Error('消息不存在');
const msg = (await NTQQMsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0]; const msg = (await NTQQMsgApi.getMsgsByMsgId(msgIdPeer.Peer, [msgIdPeer.MsgId])).msgList[0];

View File

@@ -15,9 +15,9 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetCollectionList extends BaseAction<Payload, any> { export class GetCollectionList extends BaseAction<Payload, any> {
actionName = ActionName.GetCollectionList; actionName = ActionName.GetCollectionList;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQCollectionApi = this.CoreContext.apis.CollectionApi; const NTQQCollectionApi = this.core.apis.CollectionApi;
return await NTQQCollectionApi.getAllCollection(parseInt(payload.category.toString()), +(payload.count ?? 1)); return await NTQQCollectionApi.getAllCollection(parseInt(payload.category.toString()), +(payload.count ?? 1));
} }
} }

View File

@@ -5,7 +5,7 @@ import { ActionName } from '../types';
export class GetFriendWithCategory extends BaseAction<void, any> { export class GetFriendWithCategory extends BaseAction<void, any> {
actionName = ActionName.GetFriendsWithCategory; actionName = ActionName.GetFriendsWithCategory;
async _handle(payload: void) { async _handle(payload: void) {
return (await this.CoreContext.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({ return (await this.core.apis.FriendApi.getBuddyV2ExWithCate(true)).map(category => ({
...category, ...category,
buddyList: OB11Constructor.friendsV2(category.buddyList), buddyList: OB11Constructor.friendsV2(category.buddyList),
})); }));

View File

@@ -11,7 +11,7 @@ export default class GetGroupAddRequest extends BaseAction<null, OB11GroupReques
actionName = ActionName.GetGroupIgnoreAddRequest; actionName = ActionName.GetGroupIgnoreAddRequest;
async _handle(payload: null): Promise<OB11GroupRequestNotify[] | null> { async _handle(payload: null): Promise<OB11GroupRequestNotify[] | null> {
const data = await this.CoreContext.apis.GroupApi.getGroupIgnoreNotifies(); const data = await this.core.apis.GroupApi.getGroupIgnoreNotifies();
// log(data); // log(data);
// const notifies: GroupNotify[] = data.notifies.filter(notify => notify.status === GroupNotifyStatus.WAIT_HANDLE); // const notifies: GroupNotify[] = data.notifies.filter(notify => notify.status === GroupNotifyStatus.WAIT_HANDLE);
// const returnData: OB11GroupRequestNotify[] = []; // const returnData: OB11GroupRequestNotify[] = [];

View File

@@ -5,8 +5,8 @@ export class GetProfileLike extends BaseAction<void, any> {
actionName = ActionName.GetProfileLike; actionName = ActionName.GetProfileLike;
async _handle(payload: void) { async _handle(payload: void) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const ret = await NTQQUserApi.getProfileLike(this.CoreContext.selfInfo.uid); const ret = await NTQQUserApi.getProfileLike(this.core.selfInfo.uid);
const listdata: any[] = ret.info.userLikeInfos[0].favoriteInfo.userInfos; const listdata: any[] = ret.info.userLikeInfos[0].favoriteInfo.userInfos;
for (let i = 0; i < listdata.length; i++) { for (let i = 0; i < listdata.length; i++) {
listdata[i].uin = parseInt((await NTQQUserApi.getUinByUidV2(listdata[i].uid)) || ''); listdata[i].uin = parseInt((await NTQQUserApi.getUinByUidV2(listdata[i].uid)) || '');

View File

@@ -5,7 +5,7 @@ export class GetRobotUinRange extends BaseAction<void, Array<any>> {
actionName = ActionName.GetRobotUinRange; actionName = ActionName.GetRobotUinRange;
async _handle(payload: void) { async _handle(payload: void) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
return await NTQQUserApi.getRobotUinRange(); return await NTQQUserApi.getRobotUinRange();
} }
} }

View File

@@ -15,11 +15,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class OCRImage extends BaseAction<Payload, any> { export class OCRImage extends BaseAction<Payload, any> {
actionName = ActionName.OCRImage; actionName = ActionName.OCRImage;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQSystemApi = this.CoreContext.apis.SystemApi; const NTQQSystemApi = this.core.apis.SystemApi;
const { path, isLocal, errMsg, success } = (await uri2local(this.CoreContext.NapCatTempPath, payload.image)); const { path, isLocal, errMsg, success } = (await uri2local(this.core.NapCatTempPath, payload.image));
if (!success) { if (!success) {
throw `OCR ${payload.image}失败,image字段可能格式不正确`; throw `OCR ${payload.image}失败,image字段可能格式不正确`;
} }

View File

@@ -19,8 +19,8 @@ export class SetInputStatus extends BaseAction<Payload, any> {
actionName = ActionName.SetInputStatus; actionName = ActionName.SetInputStatus;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
let peer: Peer; let peer: Peer;
if (payload.group_id) { if (payload.group_id) {
peer = { peer = {

View File

@@ -14,10 +14,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class SetLongNick extends BaseAction<Payload, any> { export class SetLongNick extends BaseAction<Payload, any> {
actionName = ActionName.SetLongNick; actionName = ActionName.SetLongNick;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const ret = await NTQQUserApi.setLongNick(payload.longNick); const ret = await NTQQUserApi.setLongNick(payload.longNick);
return ret; return ret;
} }

View File

@@ -17,10 +17,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class SetOnlineStatus extends BaseAction<Payload, null> { export class SetOnlineStatus extends BaseAction<Payload, null> {
actionName = ActionName.SetOnlineStatus; actionName = ActionName.SetOnlineStatus;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const ret = await NTQQUserApi.setSelfOnlineStatus( const ret = await NTQQUserApi.setSelfOnlineStatus(
parseInt(payload.status.toString()), parseInt(payload.status.toString()),
parseInt(payload.extStatus.toString()), parseInt(payload.extStatus.toString()),

View File

@@ -24,8 +24,8 @@ export default class SetAvatar extends BaseAction<Payload, null> {
} }
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const { path, isLocal, errMsg, success } = (await uri2local(this.CoreContext.NapCatTempPath, payload.file)); const { path, isLocal, errMsg, success } = (await uri2local(this.core.NapCatTempPath, payload.file));
if (!success) { if (!success) {
throw `头像${payload.file}设置失败,file字段可能格式不正确`; throw `头像${payload.file}设置失败,file字段可能格式不正确`;
} }

View File

@@ -16,11 +16,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class SharePeer extends BaseAction<Payload, any> { export class SharePeer extends BaseAction<Payload, any> {
actionName = ActionName.SharePeer; actionName = ActionName.SharePeer;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
if (payload.group_id) { if (payload.group_id) {
return await NTQQGroupApi.getGroupRecommendContactArkJson(payload.group_id); return await NTQQGroupApi.getGroupRecommendContactArkJson(payload.group_id);
} else if (payload.user_id) { } else if (payload.user_id) {
@@ -41,10 +41,10 @@ type PayloadGroupEx = FromSchema<typeof SchemaDataGroupEx>;
export class ShareGroupEx extends BaseAction<PayloadGroupEx, any> { export class ShareGroupEx extends BaseAction<PayloadGroupEx, any> {
actionName = ActionName.ShareGroupEx; actionName = ActionName.ShareGroupEx;
PayloadSchema = SchemaDataGroupEx; payloadSchema = SchemaDataGroupEx;
async _handle(payload: PayloadGroupEx) { async _handle(payload: PayloadGroupEx) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
return await NTQQGroupApi.getArkJsonGroupShare(payload.group_id); return await NTQQGroupApi.getArkJsonGroupShare(payload.group_id);
} }
} }

View File

@@ -17,10 +17,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class TranslateEnWordToZn extends BaseAction<Payload, Array<any> | null> { export class TranslateEnWordToZn extends BaseAction<Payload, Array<any> | null> {
actionName = ActionName.TranslateEnWordToZn; actionName = ActionName.TranslateEnWordToZn;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQSystemApi = this.CoreContext.apis.SystemApi; const NTQQSystemApi = this.core.apis.SystemApi;
const ret = await NTQQSystemApi.translateEnWordToZn(payload.words); const ret = await NTQQSystemApi.translateEnWordToZn(payload.words);
if (ret.result !== 0) { if (ret.result !== 0) {
throw new Error('翻译失败'); throw new Error('翻译失败');

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class DelGroupFile extends BaseAction<Payload, any> { export class DelGroupFile extends BaseAction<Payload, any> {
actionName = ActionName.DelGroupFile; actionName = ActionName.DelGroupFile;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
return await NTQQGroupApi.DelGroupFile(payload.group_id.toString(), [payload.file_id]); return await NTQQGroupApi.DelGroupFile(payload.group_id.toString(), [payload.file_id]);
} }
} }

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class DelGroupFileFolder extends BaseAction<Payload, any> { export class DelGroupFileFolder extends BaseAction<Payload, any> {
actionName = ActionName.DelGroupFileFolder; actionName = ActionName.DelGroupFileFolder;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
return (await NTQQGroupApi.DelGroupFileFolder(payload.group_id.toString(), payload.folder_id)).groupFileCommonResult; return (await NTQQGroupApi.DelGroupFileFolder(payload.group_id.toString(), payload.folder_id)).groupFileCommonResult;
} }
} }

View File

@@ -26,14 +26,14 @@ const GetFileBase_PayloadSchema = {
} as const satisfies JSONSchema; } as const satisfies JSONSchema;
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> { export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
PayloadSchema: any = GetFileBase_PayloadSchema; payloadSchema: any = GetFileBase_PayloadSchema;
async _handle(payload: GetFilePayload): Promise<GetFileResponse> { async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQFileApi = this.CoreContext.apis.FileApi; const NTQQFileApi = this.core.apis.FileApi;
let UuidData: { let UuidData: {
high: string; high: string;
low: string; low: string;
@@ -90,7 +90,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
return res; return res;
} }
} catch { } catch {
this.CoreContext.context.logger.logDebug('GetFileBase Mode - 1 Error'); this.core.context.logger.logDebug('GetFileBase Mode - 1 Error');
} }
const NTSearchNameResult = (await NTQQFileApi.searchfile([payload.file])).resultItems; const NTSearchNameResult = (await NTQQFileApi.searchfile([payload.file])).resultItems;
@@ -210,7 +210,7 @@ interface GetFile_Payload extends GetFile_Payload_Internal {
export default class GetFile extends GetFileBase { export default class GetFile extends GetFileBase {
actionName = ActionName.GetFile; actionName = ActionName.GetFile;
PayloadSchema = GetFile_PayloadSchema; payloadSchema = GetFile_PayloadSchema;
async _handle(payload: GetFile_Payload): Promise<GetFileResponse> { async _handle(payload: GetFile_Payload): Promise<GetFileResponse> {
payload.file = payload.file_id; payload.file = payload.file_id;

View File

@@ -14,10 +14,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetGroupFileCount extends BaseAction<Payload, { count: number }> { export class GetGroupFileCount extends BaseAction<Payload, { count: number }> {
actionName = ActionName.GetGroupFileCount; actionName = ActionName.GetGroupFileCount;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const ret = await NTQQGroupApi.GetGroupFileCount([payload.group_id?.toString()]); const ret = await NTQQGroupApi.GetGroupFileCount([payload.group_id?.toString()]);
return { count: ret.groupFileCounts[0] }; return { count: ret.groupFileCounts[0] };
} }

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetGroupFileList extends BaseAction<Payload, { FileList: Array<any> }> { export class GetGroupFileList extends BaseAction<Payload, { FileList: Array<any> }> {
actionName = ActionName.GetGroupFileList; actionName = ActionName.GetGroupFileList;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const ret = await NTQQMsgApi.getGroupFileList(payload.group_id.toString(), { const ret = await NTQQMsgApi.getGroupFileList(payload.group_id.toString(), {
sortType: 1, sortType: 1,
fileCount: payload.file_count, fileCount: payload.file_count,

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class SetGroupFileFolder extends BaseAction<Payload, any> { export class SetGroupFileFolder extends BaseAction<Payload, any> {
actionName = ActionName.SetGroupFileFolder; actionName = ActionName.SetGroupFileFolder;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
return (await NTQQGroupApi.CreatGroupFileFolder(payload.group_id.toString(), payload.folder_name)).resultWithGroupItem; return (await NTQQGroupApi.CreatGroupFileFolder(payload.group_id.toString(), payload.folder_name)).resultWithGroupItem;
} }
} }

View File

@@ -30,12 +30,12 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GoCQHTTPDownloadFile extends BaseAction<Payload, FileResponse> { export default class GoCQHTTPDownloadFile extends BaseAction<Payload, FileResponse> {
actionName = ActionName.GoCQHTTP_DownloadFile; actionName = ActionName.GoCQHTTP_DownloadFile;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<FileResponse> { async _handle(payload: Payload): Promise<FileResponse> {
const isRandomName = !payload.name; const isRandomName = !payload.name;
const name = payload.name || randomUUID(); const name = payload.name || randomUUID();
const filePath = joinPath(this.CoreContext.NapCatTempPath, name); const filePath = joinPath(this.core.NapCatTempPath, name);
if (payload.base64) { if (payload.base64) {
fs.writeFileSync(filePath, payload.base64, 'base64'); fs.writeFileSync(filePath, payload.base64, 'base64');
@@ -51,7 +51,7 @@ export default class GoCQHTTPDownloadFile extends BaseAction<Payload, FileRespon
if (isRandomName) { if (isRandomName) {
// 默认实现要名称未填写时文件名为文件 md5 // 默认实现要名称未填写时文件名为文件 md5
const md5 = await calculateFileMD5(filePath); const md5 = await calculateFileMD5(filePath);
const newPath = joinPath(this.CoreContext.NapCatTempPath, md5); const newPath = joinPath(this.core.NapCatTempPath, md5);
fs.renameSync(filePath, newPath); fs.renameSync(filePath, newPath);
return { file: newPath }; return { file: newPath };
} }

View File

@@ -20,10 +20,10 @@ interface Response {
export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> { export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
actionName = ActionName.GoCQHTTP_GetForwardMsg; actionName = ActionName.GoCQHTTP_GetForwardMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const msgId = payload.message_id || payload.id; const msgId = payload.message_id || payload.id;
if (!msgId) { if (!msgId) {
throw Error('message_id is required'); throw Error('message_id is required');
@@ -39,7 +39,7 @@ export class GoCQHTTPGetForwardMsgAction extends BaseAction<Payload, any> {
} }
const msgList = data.msgList; const msgList = data.msgList;
const messages = (await Promise.all(msgList.map(async msg => { const messages = (await Promise.all(msgList.map(async msg => {
const resMsg = await this.OneBotContext.apiContext.MsgApi const resMsg = await this.obContext.apiContext.MsgApi
.parseMessage(msg); .parseMessage(msg);
if (!resMsg) return; if (!resMsg) return;
resMsg.message_id = MessageUnique.createMsg({ resMsg.message_id = MessageUnique.createMsg({

View File

@@ -24,12 +24,12 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GetFriendMsgHistory extends BaseAction<Payload, Response> { export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
actionName = ActionName.GetFriendMsgHistory; actionName = ActionName.GetFriendMsgHistory;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<Response> { async _handle(payload: Payload): Promise<Response> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
//处理参数 //处理参数
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
const MsgCount = +(payload.count ?? 20); const MsgCount = +(payload.count ?? 20);
@@ -53,7 +53,7 @@ export default class GetFriendMsgHistory extends BaseAction<Payload, Response> {
})); }));
//转换消息 //转换消息
const ob11MsgList = (await Promise.all( const ob11MsgList = (await Promise.all(
msgList.map(msg => this.OneBotContext.apiContext.MsgApi.parseMessage(msg))) msgList.map(msg => this.obContext.apiContext.MsgApi.parseMessage(msg)))
).filter(msg => msg !== undefined); ).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };
} }

View File

@@ -16,13 +16,13 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetGroupHonorInfo extends BaseAction<Payload, Array<any>> { export class GetGroupHonorInfo extends BaseAction<Payload, Array<any>> {
actionName = ActionName.GetGroupHonorInfo; actionName = ActionName.GetGroupHonorInfo;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
if (!payload.type) { if (!payload.type) {
payload.type = WebHonorType.ALL; payload.type = WebHonorType.ALL;
} }
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.core.apis.WebApi;
return await NTQQWebApi.getGroupHonorInfo(payload.group_id.toString(), payload.type); return await NTQQWebApi.getGroupHonorInfo(payload.group_id.toString(), payload.type);
} }
} }

View File

@@ -24,10 +24,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Response> { export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Response> {
actionName = ActionName.GoCQHTTP_GetGroupMsgHistory; actionName = ActionName.GoCQHTTP_GetGroupMsgHistory;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<Response> { async _handle(payload: Payload): Promise<Response> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
//处理参数 //处理参数
const isReverseOrder = payload.reverseOrder || true; const isReverseOrder = payload.reverseOrder || true;
const MsgCount = +(payload.count ?? 20); const MsgCount = +(payload.count ?? 20);
@@ -48,7 +48,7 @@ export default class GoCQHTTPGetGroupMsgHistory extends BaseAction<Payload, Resp
//转换消息 //转换消息
const ob11MsgList = (await Promise.all( const ob11MsgList = (await Promise.all(
msgList.map(msg => this.OneBotContext.apiContext.MsgApi.parseMessage(msg))) msgList.map(msg => this.obContext.apiContext.MsgApi.parseMessage(msg)))
).filter(msg => msg !== undefined); ).filter(msg => msg !== undefined);
return { 'messages': ob11MsgList }; return { 'messages': ob11MsgList };
} }

View File

@@ -15,7 +15,7 @@ export class GetOnlineClient extends BaseAction<void, Array<any>> {
async _handle(payload: void) { async _handle(payload: void) {
//注册监听 //注册监听
const NTQQSystemApi = this.CoreContext.apis.SystemApi; const NTQQSystemApi = this.core.apis.SystemApi;
NTQQSystemApi.getOnlineDev(); NTQQSystemApi.getOnlineDev();
await sleep(500); await sleep(500);

View File

@@ -19,7 +19,7 @@ export default class GoCQHTTPGetStrangerInfo extends BaseAction<Payload, OB11Use
actionName = ActionName.GoCQHTTP_GetStrangerInfo; actionName = ActionName.GoCQHTTP_GetStrangerInfo;
async _handle(payload: Payload): Promise<OB11User> { async _handle(payload: Payload): Promise<OB11User> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const user_id = payload.user_id.toString(); const user_id = payload.user_id.toString();
const extendData = await NTQQUserApi.getUserDetailInfoByUinV2(user_id); const extendData = await NTQQUserApi.getUserDetailInfoByUinV2(user_id);
const uid = (await NTQQUserApi.getUidByUinV2(user_id))!; const uid = (await NTQQUserApi.getUidByUinV2(user_id))!;

View File

@@ -12,7 +12,7 @@ export class GoCQHTTPHandleQuickAction extends BaseAction<Payload, null> {
actionName = ActionName.GoCQHTTP_HandleQuickAction; actionName = ActionName.GoCQHTTP_HandleQuickAction;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
handleQuickOperation(this.CoreContext, this.OneBotContext, payload.context, payload.operation).then().catch(this.CoreContext.context.logger.logError); handleQuickOperation(this.core, this.obContext, payload.context, payload.operation).then().catch(this.core.context.logger.logError);
return null; return null;
} }
} }

View File

@@ -22,7 +22,7 @@ export class SendGroupNotice extends BaseAction<Payload, null> {
actionName = ActionName.GoCQHTTP_SendGroupNotice; actionName = ActionName.GoCQHTTP_SendGroupNotice;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
let UploadImage: { id: string, width: number, height: number } | undefined = undefined; let UploadImage: { id: string, width: number, height: number } | undefined = undefined;
if (payload.image) { if (payload.image) {
//公告图逻辑 //公告图逻辑
@@ -31,7 +31,7 @@ export class SendGroupNotice extends BaseAction<Payload, null> {
path, path,
isLocal, isLocal,
success, success,
} = (await uri2local(this.CoreContext.NapCatTempPath, payload.image)); } = (await uri2local(this.core.NapCatTempPath, payload.image));
if (!success) { if (!success) {
throw `群公告${payload.image}设置失败,image字段可能格式不正确`; throw `群公告${payload.image}设置失败,image字段可能格式不正确`;
} }

View File

@@ -27,8 +27,8 @@ export default class SetGroupPortrait extends BaseAction<Payload, any> {
} }
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const { path, isLocal, errMsg, success } = (await uri2local(this.CoreContext.NapCatTempPath, payload.file)); const { path, isLocal, errMsg, success } = (await uri2local(this.core.NapCatTempPath, payload.file));
if (!success) { if (!success) {
throw `头像${payload.file}设置失败,file字段可能格式不正确`; throw `头像${payload.file}设置失败,file字段可能格式不正确`;
} }

View File

@@ -16,11 +16,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class SetQQProfile extends BaseAction<Payload, any | null> { export class SetQQProfile extends BaseAction<Payload, any | null> {
actionName = ActionName.SetQQProfile; actionName = ActionName.SetQQProfile;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const self = this.CoreContext.selfInfo; const self = this.core.selfInfo;
const OldProfile = await NTQQUserApi.getUserDetailInfo(self.uid); const OldProfile = await NTQQUserApi.getUserDetailInfo(self.uid);
const ret = await NTQQUserApi.modifySelfProfile({ const ret = await NTQQUserApi.modifySelfProfile({
nick: payload.nickname, nick: payload.nickname,

View File

@@ -22,19 +22,19 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GoCQHTTPUploadGroupFile extends BaseAction<Payload, null> { export default class GoCQHTTPUploadGroupFile extends BaseAction<Payload, null> {
actionName = ActionName.GoCQHTTP_UploadGroupFile; actionName = ActionName.GoCQHTTP_UploadGroupFile;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
let file = payload.file; let file = payload.file;
if (fs.existsSync(file)) { if (fs.existsSync(file)) {
file = `file://${file}`; file = `file://${file}`;
} }
const downloadResult = await uri2local(this.CoreContext.NapCatTempPath, file); const downloadResult = await uri2local(this.core.NapCatTempPath, file);
if (!downloadResult.success) { if (!downloadResult.success) {
throw new Error(downloadResult.errMsg); throw new Error(downloadResult.errMsg);
} }
const sendFileEle = await this.CoreContext.apis.FileApi.createValidSendFileElement(downloadResult.path, payload.name, payload.folder_id); const sendFileEle = await this.core.apis.FileApi.createValidSendFileElement(downloadResult.path, payload.name, payload.folder_id);
await sendMsg(this.CoreContext, { await sendMsg(this.core, {
chatType: ChatType.KCHATTYPEGROUP, chatType: ChatType.KCHATTYPEGROUP,
peerUid: payload.group_id.toString(), peerUid: payload.group_id.toString(),
}, [sendFileEle], [], true); }, [sendFileEle], [], true);

View File

@@ -20,11 +20,11 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GoCQHTTPUploadPrivateFile extends BaseAction<Payload, null> { export default class GoCQHTTPUploadPrivateFile extends BaseAction<Payload, null> {
actionName = ActionName.GOCQHTTP_UploadPrivateFile; actionName = ActionName.GOCQHTTP_UploadPrivateFile;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async getPeer(payload: Payload): Promise<Peer> { async getPeer(payload: Payload): Promise<Peer> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
if (payload.user_id) { if (payload.user_id) {
const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!peerUid) { if (!peerUid) {
@@ -42,12 +42,12 @@ export default class GoCQHTTPUploadPrivateFile extends BaseAction<Payload, null>
if (fs.existsSync(file)) { if (fs.existsSync(file)) {
file = `file://${file}`; file = `file://${file}`;
} }
const downloadResult = await uri2local(this.CoreContext.NapCatTempPath, file); const downloadResult = await uri2local(this.core.NapCatTempPath, file);
if (!downloadResult.success) { if (!downloadResult.success) {
throw new Error(downloadResult.errMsg); throw new Error(downloadResult.errMsg);
} }
const sendFileEle: SendFileElement = await this.CoreContext.apis.FileApi.createValidSendFileElement(downloadResult.path, payload.name); const sendFileEle: SendFileElement = await this.core.apis.FileApi.createValidSendFileElement(downloadResult.path, payload.name);
await sendMsg(this.CoreContext, peer, [sendFileEle], [], true); await sendMsg(this.core, peer, [sendFileEle], [], true);
return null; return null;
} }
} }

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class DelEssenceMsg extends BaseAction<Payload, any> { export default class DelEssenceMsg extends BaseAction<Payload, any> {
actionName = ActionName.DelEssenceMsg; actionName = ActionName.DelEssenceMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) throw new Error('msg not found'); if (!msg) throw new Error('msg not found');
return await NTQQGroupApi.removeGroupEssence( return await NTQQGroupApi.removeGroupEssence(

View File

@@ -17,10 +17,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class DelGroupNotice extends BaseAction<Payload, any> { export class DelGroupNotice extends BaseAction<Payload, any> {
actionName = ActionName.DelGroupNotice; actionName = ActionName.DelGroupNotice;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const group = payload.group_id.toString(); const group = payload.group_id.toString();
const feedId = payload.feed_id; const feedId = payload.feed_id;
return await NTQQGroupApi.deleteGroupBulletin(group, feedId); return await NTQQGroupApi.deleteGroupBulletin(group, feedId);

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetGroupEssence extends BaseAction<Payload, GroupEssenceMsgRet> { export class GetGroupEssence extends BaseAction<Payload, GroupEssenceMsgRet> {
actionName = ActionName.GoCQHTTP_GetEssenceMsg; actionName = ActionName.GoCQHTTP_GetEssenceMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.core.apis.WebApi;
const ret = await NTQQWebApi.getGroupEssenceMsg(payload.group_id.toString(), (payload.pages || "0").toString()); const ret = await NTQQWebApi.getGroupEssenceMsg(payload.group_id.toString(), (payload.pages || "0").toString());
if (!ret) { if (!ret) {
throw new Error('获取失败'); throw new Error('获取失败');

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
class GetGroupInfo extends BaseAction<Payload, OB11Group> { class GetGroupInfo extends BaseAction<Payload, OB11Group> {
actionName = ActionName.GetGroupInfo; actionName = ActionName.GetGroupInfo;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const group = (await NTQQGroupApi.getGroups()).find(e => e.groupCode == payload.group_id.toString()); const group = (await NTQQGroupApi.getGroups()).find(e => e.groupCode == payload.group_id.toString());
if (!group) throw `${payload.group_id}不存在`; if (!group) throw `${payload.group_id}不存在`;
return OB11Constructor.group(group); return OB11Constructor.group(group);

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
class GetGroupList extends BaseAction<Payload, OB11Group[]> { class GetGroupList extends BaseAction<Payload, OB11Group[]> {
actionName = ActionName.GetGroupList; actionName = ActionName.GetGroupList;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const groupList: Group[] = await NTQQGroupApi.getGroups(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache); const groupList: Group[] = await NTQQGroupApi.getGroups(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache);
return OB11Constructor.groups(groupList); return OB11Constructor.groups(groupList);
} }

View File

@@ -19,11 +19,11 @@ type Payload = FromSchema<typeof SchemaData>;
class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> { class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
actionName = ActionName.GetGroupMemberInfo; actionName = ActionName.GetGroupMemberInfo;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const isNocache = typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache; const isNocache = typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache;
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error (`Uin2Uid Error ${payload.user_id}不存在`); if (!uid) throw new Error (`Uin2Uid Error ${payload.user_id}不存在`);
@@ -33,14 +33,14 @@ class GetGroupMemberInfo extends BaseAction<Payload, OB11GroupMember> {
]); ]);
if (member.status !== 'fulfilled') throw new Error (`群(${payload.group_id})成员${payload.user_id}不存在 ${member.reason}`); if (member.status !== 'fulfilled') throw new Error (`群(${payload.group_id})成员${payload.user_id}不存在 ${member.reason}`);
if (info.status === 'fulfilled') { if (info.status === 'fulfilled') {
this.CoreContext.context.logger.logDebug("群成员详细信息结果", info.value); this.core.context.logger.logDebug("群成员详细信息结果", info.value);
Object.assign(member, info.value); Object.assign(member, info.value);
} else { } else {
this.CoreContext.context.logger.logDebug(`获取群成员详细信息失败, 只能返回基础信息 ${info.reason}`); this.core.context.logger.logDebug(`获取群成员详细信息失败, 只能返回基础信息 ${info.reason}`);
} }
const date = Math.round(Date.now() / 1000); const date = Math.round(Date.now() / 1000);
const retMember = OB11Constructor.groupMember(payload.group_id.toString(), member.value as GroupMember); const retMember = OB11Constructor.groupMember(payload.group_id.toString(), member.value as GroupMember);
const Member = await this.CoreContext.apis.GroupApi.getGroupMember(payload.group_id.toString(), retMember.user_id); const Member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), retMember.user_id);
retMember.last_sent_time = parseInt(Member?.lastSpeakTime || date.toString()); retMember.last_sent_time = parseInt(Member?.lastSpeakTime || date.toString());
retMember.join_time = parseInt(Member?.joinTime || date.toString()); retMember.join_time = parseInt(Member?.joinTime || date.toString());
return retMember; return retMember;

View File

@@ -17,11 +17,11 @@ type Payload = FromSchema<typeof SchemaData>;
class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> { class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
actionName = ActionName.GetGroupMemberList; actionName = ActionName.GetGroupMemberList;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.core.apis.WebApi;
const groupMembers = await NTQQGroupApi.getGroupMembers(payload.group_id.toString()); const groupMembers = await NTQQGroupApi.getGroupMembers(payload.group_id.toString());
const groupMembersArr = Array.from(groupMembers.values()); const groupMembersArr = Array.from(groupMembers.values());
@@ -39,7 +39,7 @@ class GetGroupMemberList extends BaseAction<Payload, OB11GroupMember[]> {
MemberMap.set(_groupMembers[i].user_id, _groupMembers[i]); MemberMap.set(_groupMembers[i].user_id, _groupMembers[i]);
} }
const selfRole = groupMembers.get(this.CoreContext.selfInfo.uid)?.role; const selfRole = groupMembers.get(this.core.selfInfo.uid)?.role;
const isPrivilege = selfRole === 3 || selfRole === 4; const isPrivilege = selfRole === 3 || selfRole === 4;
_groupMembers.forEach(item => { _groupMembers.forEach(item => {

View File

@@ -31,10 +31,10 @@ type ApiGroupNotice = GroupNotice & WebApiGroupNoticeFeed;
export class GetGroupNotice extends BaseAction<Payload, GroupNotice[]> { export class GetGroupNotice extends BaseAction<Payload, GroupNotice[]> {
actionName = ActionName.GoCQHTTP_GetGroupNotice; actionName = ActionName.GoCQHTTP_GetGroupNotice;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.core.apis.WebApi;
const group = payload.group_id.toString(); const group = payload.group_id.toString();
const ret = await NTQQWebApi.getGroupNotice(group); const ret = await NTQQWebApi.getGroupNotice(group);

View File

@@ -16,8 +16,8 @@ export class GetGroupSystemMsg extends BaseAction<void, any> {
actionName = ActionName.GetGroupSystemMsg; actionName = ActionName.GetGroupSystemMsg;
async _handle(payload: void) { async _handle(payload: void) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
// 默认10条 该api未完整实现 包括响应数据规范化 类型规范化 // 默认10条 该api未完整实现 包括响应数据规范化 类型规范化
const SingleScreenNotifies = await NTQQGroupApi.getSingleScreenNotifies(10); const SingleScreenNotifies = await NTQQGroupApi.getSingleScreenNotifies(10);
const retData: any = { InvitedRequest: [], join_requests: [] }; const retData: any = { InvitedRequest: [], join_requests: [] };

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetEssenceMsg extends BaseAction<Payload, any> { export default class SetEssenceMsg extends BaseAction<Payload, any> {
actionName = ActionName.SetEssenceMsg; actionName = ActionName.SetEssenceMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error('msg not found'); throw new Error('msg not found');

View File

@@ -17,10 +17,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupAddRequest extends BaseAction<Payload, null> { export default class SetGroupAddRequest extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupAddRequest; actionName = ActionName.SetGroupAddRequest;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const flag = payload.flag.toString(); const flag = payload.flag.toString();
const approve = payload.approve?.toString() !== 'false'; const approve = payload.approve?.toString() !== 'false';
await NTQQGroupApi.handleGroupRequest(flag, await NTQQGroupApi.handleGroupRequest(flag,

View File

@@ -17,12 +17,12 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupAdmin extends BaseAction<Payload, null> { export default class SetGroupAdmin extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupAdmin; actionName = ActionName.SetGroupAdmin;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const enable = typeof payload.enable === 'string' ? payload.enable === 'true' : !!payload.enable; const enable = typeof payload.enable === 'string' ? payload.enable === 'true' : !!payload.enable;
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('get Uid Error'); if (!uid) throw new Error('get Uid Error');
await NTQQGroupApi.setMemberRole(payload.group_id.toString(), uid, enable ? GroupMemberRole.admin : GroupMemberRole.normal); await NTQQGroupApi.setMemberRole(payload.group_id.toString(), uid, enable ? GroupMemberRole.admin : GroupMemberRole.normal);

View File

@@ -16,11 +16,11 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupBan extends BaseAction<Payload, null> { export default class SetGroupBan extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupBan; actionName = ActionName.SetGroupBan;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('uid error'); if (!uid) throw new Error('uid error');
await NTQQGroupApi.banMember(payload.group_id.toString(), await NTQQGroupApi.banMember(payload.group_id.toString(),

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupCard extends BaseAction<Payload, null> { export default class SetGroupCard extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupCard; actionName = ActionName.SetGroupCard;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const member = await NTQQGroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString()); const member = await NTQQGroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
member && await NTQQGroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || ''); member && await NTQQGroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || '');
return null; return null;

View File

@@ -17,11 +17,11 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupKick extends BaseAction<Payload, null> { export default class SetGroupKick extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupKick; actionName = ActionName.SetGroupKick;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const rejectReq = payload.reject_add_request?.toString() == 'true'; const rejectReq = payload.reject_add_request?.toString() == 'true';
const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const uid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!uid) throw new Error('get Uid Error'); if (!uid) throw new Error('get Uid Error');

View File

@@ -14,10 +14,10 @@ const SchemaData = {
type Payload = FromSchema<typeof SchemaData>; type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupLeave extends BaseAction<Payload, any> { export default class SetGroupLeave extends BaseAction<Payload, any> {
actionName = ActionName.SetGroupLeave; actionName = ActionName.SetGroupLeave;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<any> { async _handle(payload: Payload): Promise<any> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
await NTQQGroupApi.quitGroup(payload.group_id.toString()); await NTQQGroupApi.quitGroup(payload.group_id.toString());
} }
} }

View File

@@ -14,10 +14,10 @@ const SchemaData = {
type Payload = FromSchema<typeof SchemaData>; type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupName extends BaseAction<Payload, null> { export default class SetGroupName extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupName; actionName = ActionName.SetGroupName;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
await NTQQGroupApi.setGroupName(payload.group_id.toString(), payload.group_name); await NTQQGroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
return null; return null;
} }

View File

@@ -15,11 +15,11 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetGroupWholeBan extends BaseAction<Payload, null> { export default class SetGroupWholeBan extends BaseAction<Payload, null> {
actionName = ActionName.SetGroupWholeBan; actionName = ActionName.SetGroupWholeBan;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const enable = payload.enable?.toString() !== 'false'; const enable = payload.enable?.toString() !== 'false';
const NTQQGroupApi = this.CoreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
await NTQQGroupApi.banGroup(payload.group_id.toString(), enable); await NTQQGroupApi.banGroup(payload.group_id.toString(), enable);
return null; return null;
} }

View File

@@ -84,93 +84,93 @@ import { DelGroupNotice } from './group/DelGroupNotice';
export type ActionMap = Map<string, BaseAction<any, any>>; export type ActionMap = Map<string, BaseAction<any, any>>;
export function createActionMap(onebotContext: NapCatOneBot11Adapter, coreContext: NapCatCore): ActionMap { export function createActionMap(obContext: NapCatOneBot11Adapter, core: NapCatCore): ActionMap {
const actionHandlers = [ const actionHandlers = [
new FetchEmojiLike(onebotContext, coreContext), new FetchEmojiLike(obContext, core),
new GetFile(onebotContext, coreContext), new GetFile(obContext, core),
new SetQQProfile(onebotContext, coreContext), new SetQQProfile(obContext, core),
new ShareGroupEx(onebotContext, coreContext), new ShareGroupEx(obContext, core),
new SharePeer(onebotContext, coreContext), new SharePeer(obContext, core),
new CreateCollection(onebotContext, coreContext), new CreateCollection(obContext, core),
new SetLongNick(onebotContext, coreContext), new SetLongNick(obContext, core),
new ForwardFriendSingleMsg(onebotContext, coreContext), new ForwardFriendSingleMsg(obContext, core),
new ForwardGroupSingleMsg(onebotContext, coreContext), new ForwardGroupSingleMsg(obContext, core),
new MarkGroupMsgAsRead(onebotContext, coreContext), new MarkGroupMsgAsRead(obContext, core),
new MarkPrivateMsgAsRead(onebotContext, coreContext), new MarkPrivateMsgAsRead(obContext, core),
new SetQQAvatar(onebotContext, coreContext), new SetQQAvatar(obContext, core),
new TranslateEnWordToZn(onebotContext, coreContext), new TranslateEnWordToZn(obContext, core),
new GetGroupFileCount(onebotContext, coreContext), new GetGroupFileCount(obContext, core),
new GetGroupFileList(onebotContext, coreContext), new GetGroupFileList(obContext, core),
new SetGroupFileFolder(onebotContext, coreContext), new SetGroupFileFolder(obContext, core),
new DelGroupFile(onebotContext, coreContext), new DelGroupFile(obContext, core),
new DelGroupFileFolder(onebotContext, coreContext), new DelGroupFileFolder(obContext, core),
// onebot11 // onebot11
new SendLike(onebotContext, coreContext), new SendLike(obContext, core),
new GetMsg(onebotContext, coreContext), new GetMsg(obContext, core),
new GetLoginInfo(onebotContext, coreContext), new GetLoginInfo(obContext, core),
new GetFriendList(onebotContext, coreContext), new GetFriendList(obContext, core),
new GetGroupList(onebotContext, coreContext), new GetGroupList(obContext, core),
new GetGroupInfo(onebotContext, coreContext), new GetGroupInfo(obContext, core),
new GetGroupMemberList(onebotContext, coreContext), new GetGroupMemberList(obContext, core),
new GetGroupMemberInfo(onebotContext, coreContext), new GetGroupMemberInfo(obContext, core),
new SendGroupMsg(onebotContext, coreContext), new SendGroupMsg(obContext, core),
new SendPrivateMsg(onebotContext, coreContext), new SendPrivateMsg(obContext, core),
new SendMsg(onebotContext, coreContext), new SendMsg(obContext, core),
new DeleteMsg(onebotContext, coreContext), new DeleteMsg(obContext, core),
new SetGroupAddRequest(onebotContext, coreContext), new SetGroupAddRequest(obContext, core),
new SetFriendAddRequest(onebotContext, coreContext), new SetFriendAddRequest(obContext, core),
new SetGroupLeave(onebotContext, coreContext), new SetGroupLeave(obContext, core),
new GetVersionInfo(onebotContext, coreContext), new GetVersionInfo(obContext, core),
new CanSendRecord(onebotContext, coreContext), new CanSendRecord(obContext, core),
new CanSendImage(onebotContext, coreContext), new CanSendImage(obContext, core),
new GetStatus(onebotContext, coreContext), new GetStatus(obContext, core),
new SetGroupWholeBan(onebotContext, coreContext), new SetGroupWholeBan(obContext, core),
new SetGroupBan(onebotContext, coreContext), new SetGroupBan(obContext, core),
new SetGroupKick(onebotContext, coreContext), new SetGroupKick(obContext, core),
new SetGroupAdmin(onebotContext, coreContext), new SetGroupAdmin(obContext, core),
new SetGroupName(onebotContext, coreContext), new SetGroupName(obContext, core),
new SetGroupCard(onebotContext, coreContext), new SetGroupCard(obContext, core),
new GetImage(onebotContext, coreContext), new GetImage(obContext, core),
new GetRecord(onebotContext, coreContext), new GetRecord(obContext, core),
new SetMsgEmojiLike(onebotContext, coreContext), new SetMsgEmojiLike(obContext, core),
new GetCookies(onebotContext, coreContext), new GetCookies(obContext, core),
new SetOnlineStatus(onebotContext, coreContext), new SetOnlineStatus(obContext, core),
new GetRobotUinRange(onebotContext, coreContext), new GetRobotUinRange(obContext, core),
new GetFriendWithCategory(onebotContext, coreContext), new GetFriendWithCategory(obContext, core),
//以下为go-cqhttp api //以下为go-cqhttp api
new GetOnlineClient(onebotContext, coreContext), new GetOnlineClient(obContext, core),
new OCRImage(onebotContext, coreContext), new OCRImage(obContext, core),
new IOCRImage(onebotContext, coreContext), new IOCRImage(obContext, core),
new GetGroupHonorInfo(onebotContext, coreContext), new GetGroupHonorInfo(obContext, core),
new SendGroupNotice(onebotContext, coreContext), new SendGroupNotice(obContext, core),
new GetGroupNotice(onebotContext, coreContext), new GetGroupNotice(obContext, core),
new GetGroupEssence(onebotContext, coreContext), new GetGroupEssence(obContext, core),
new GoCQHTTPSendForwardMsg(onebotContext, coreContext), new GoCQHTTPSendForwardMsg(obContext, core),
new GoCQHTTPSendGroupForwardMsg(onebotContext, coreContext), new GoCQHTTPSendGroupForwardMsg(obContext, core),
new GoCQHTTPSendPrivateForwardMsg(onebotContext, coreContext), new GoCQHTTPSendPrivateForwardMsg(obContext, core),
new GoCQHTTPGetStrangerInfo(onebotContext, coreContext), new GoCQHTTPGetStrangerInfo(obContext, core),
new GoCQHTTPDownloadFile(onebotContext, coreContext), new GoCQHTTPDownloadFile(obContext, core),
new GetGuildList(onebotContext, coreContext), new GetGuildList(obContext, core),
new GoCQHTTPMarkMsgAsRead(onebotContext, coreContext), new GoCQHTTPMarkMsgAsRead(obContext, core),
new GoCQHTTPUploadGroupFile(onebotContext, coreContext), new GoCQHTTPUploadGroupFile(obContext, core),
new GoCQHTTPGetGroupMsgHistory(onebotContext, coreContext), new GoCQHTTPGetGroupMsgHistory(obContext, core),
new GoCQHTTPGetForwardMsgAction(onebotContext, coreContext), new GoCQHTTPGetForwardMsgAction(obContext, core),
new GetFriendMsgHistory(onebotContext, coreContext), new GetFriendMsgHistory(obContext, core),
new GoCQHTTPHandleQuickAction(onebotContext, coreContext), new GoCQHTTPHandleQuickAction(obContext, core),
new GetGroupSystemMsg(onebotContext, coreContext), new GetGroupSystemMsg(obContext, core),
new DelEssenceMsg(onebotContext, coreContext), new DelEssenceMsg(obContext, core),
new SetEssenceMsg(onebotContext, coreContext), new SetEssenceMsg(obContext, core),
new GetRecentContact(onebotContext, coreContext), new GetRecentContact(obContext, core),
new MarkAllMsgAsRead(onebotContext, coreContext), new MarkAllMsgAsRead(obContext, core),
new GetProfileLike(onebotContext, coreContext), new GetProfileLike(obContext, core),
new SetGroupPortrait(onebotContext, coreContext), new SetGroupPortrait(obContext, core),
new FetchCustomFace(onebotContext, coreContext), new FetchCustomFace(obContext, core),
new GoCQHTTPUploadPrivateFile(onebotContext, coreContext), new GoCQHTTPUploadPrivateFile(obContext, core),
new GetGuildProfile(onebotContext, coreContext), new GetGuildProfile(obContext, core),
new SetModelShow(onebotContext, coreContext), new SetModelShow(obContext, core),
new SetInputStatus(onebotContext, coreContext), new SetInputStatus(obContext, core),
new GetCSRF(onebotContext, coreContext), new GetCSRF(obContext, core),
new DelGroupNotice(onebotContext, coreContext), new DelGroupNotice(obContext, core),
]; ];
const actionMap = new Map(); const actionMap = new Map();
for (const action of actionHandlers) { for (const action of actionHandlers) {

View File

@@ -21,13 +21,13 @@ type Payload = FromSchema<typeof SchemaData>;
class DeleteMsg extends BaseAction<Payload, void> { class DeleteMsg extends BaseAction<Payload, void> {
actionName = ActionName.DeleteMsg; actionName = ActionName.DeleteMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(Number(payload.message_id)); const msg = MessageUnique.getMsgIdAndPeerByShortId(Number(payload.message_id));
if (msg) { if (msg) {
const ret = this.CoreContext.eventWrapper.RegisterListen<NodeIKernelMsgListener['onMsgInfoListUpdate']> const ret = this.core.eventWrapper.RegisterListen<NodeIKernelMsgListener['onMsgInfoListUpdate']>
( (
'NodeIKernelMsgListener/onMsgInfoListUpdate', 'NodeIKernelMsgListener/onMsgInfoListUpdate',
1, 1,

View File

@@ -18,7 +18,7 @@ type Payload = FromSchema<typeof SchemaData>;
class ForwardSingleMsg extends BaseAction<Payload, null> { class ForwardSingleMsg extends BaseAction<Payload, null> {
protected async getTargetPeer(payload: Payload): Promise<Peer> { protected async getTargetPeer(payload: Payload): Promise<Peer> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
if (payload.user_id) { if (payload.user_id) {
const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!peerUid) { if (!peerUid) {
@@ -30,7 +30,7 @@ class ForwardSingleMsg extends BaseAction<Payload, null> {
} }
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error(`无法找到消息${payload.message_id}`); throw new Error(`无法找到消息${payload.message_id}`);
@@ -48,11 +48,11 @@ class ForwardSingleMsg extends BaseAction<Payload, null> {
} }
export class ForwardFriendSingleMsg extends ForwardSingleMsg { export class ForwardFriendSingleMsg extends ForwardSingleMsg {
PayloadSchema = SchemaData; payloadSchema = SchemaData;
actionName = ActionName.ForwardFriendSingleMsg; actionName = ActionName.ForwardFriendSingleMsg;
} }
export class ForwardGroupSingleMsg extends ForwardSingleMsg { export class ForwardGroupSingleMsg extends ForwardSingleMsg {
PayloadSchema = SchemaData; payloadSchema = SchemaData;
actionName = ActionName.ForwardGroupSingleMsg; actionName = ActionName.ForwardGroupSingleMsg;
} }

View File

@@ -19,10 +19,10 @@ type Payload = FromSchema<typeof SchemaData>;
class GetMsg extends BaseAction<Payload, OB11Message> { class GetMsg extends BaseAction<Payload, OB11Message> {
actionName = ActionName.GetMsg; actionName = ActionName.GetMsg;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
// log("history msg ids", Object.keys(msgHistory)); // log("history msg ids", Object.keys(msgHistory));
if (!payload.message_id) { if (!payload.message_id) {
throw Error('参数message_id不能为空'); throw Error('参数message_id不能为空');
@@ -36,7 +36,7 @@ class GetMsg extends BaseAction<Payload, OB11Message> {
const msg = await NTQQMsgApi.getMsgsByMsgId( const msg = await NTQQMsgApi.getMsgsByMsgId(
peer, peer,
[msgIdWithPeer?.MsgId || payload.message_id.toString()]); [msgIdWithPeer?.MsgId || payload.message_id.toString()]);
const retMsg = await this.OneBotContext.apiContext.MsgApi.parseMessage(msg.msgList[0], 'array'); const retMsg = await this.obContext.apiContext.MsgApi.parseMessage(msg.msgList[0], 'array');
if (!retMsg) throw Error('消息为空'); if (!retMsg) throw Error('消息为空');
try { try {
retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!; retMsg.message_id = MessageUnique.createMsg(peer, msg.msgList[0].msgId)!;

View File

@@ -15,8 +15,8 @@ type PlayloadType = FromSchema<typeof SchemaData>;
class MarkMsgAsRead extends BaseAction<PlayloadType, null> { class MarkMsgAsRead extends BaseAction<PlayloadType, null> {
async getPeer(payload: PlayloadType): Promise<Peer> { async getPeer(payload: PlayloadType): Promise<Peer> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
if (payload.user_id) { if (payload.user_id) {
const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString()); const peerUid = await NTQQUserApi.getUidByUinV2(payload.user_id.toString());
if (!peerUid) { if (!peerUid) {
@@ -32,7 +32,7 @@ class MarkMsgAsRead extends BaseAction<PlayloadType, null> {
} }
async _handle(payload: PlayloadType): Promise<null> { async _handle(payload: PlayloadType): Promise<null> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
// 调用API // 调用API
const ret = await NTQQMsgApi.setMsgRead(await this.getPeer(payload)); const ret = await NTQQMsgApi.setMsgRead(await this.getPeer(payload));
if (ret.result != 0) { if (ret.result != 0) {
@@ -44,12 +44,12 @@ class MarkMsgAsRead extends BaseAction<PlayloadType, null> {
// 以下为非标准实现 // 以下为非标准实现
export class MarkPrivateMsgAsRead extends MarkMsgAsRead { export class MarkPrivateMsgAsRead extends MarkMsgAsRead {
PayloadSchema = SchemaData; payloadSchema = SchemaData;
actionName = ActionName.MarkPrivateMsgAsRead; actionName = ActionName.MarkPrivateMsgAsRead;
} }
export class MarkGroupMsgAsRead extends MarkMsgAsRead { export class MarkGroupMsgAsRead extends MarkMsgAsRead {
PayloadSchema = SchemaData; payloadSchema = SchemaData;
actionName = ActionName.MarkGroupMsgAsRead; actionName = ActionName.MarkGroupMsgAsRead;
} }
@@ -70,7 +70,7 @@ export class MarkAllMsgAsRead extends BaseAction<Payload, null> {
actionName = ActionName._MarkAllMsgAsRead; actionName = ActionName._MarkAllMsgAsRead;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
await NTQQMsgApi.markallMsgAsRead(); await NTQQMsgApi.markallMsgAsRead();
return null; return null;
} }

View File

@@ -32,9 +32,9 @@ export function normalize(message: OB11MessageMixType, autoEscape = false): OB11
) : Array.isArray(message) ? message : [message]; ) : Array.isArray(message) ? message : [message];
} }
export async function sendMsg(coreContext: NapCatCore, peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], waitComplete = true) { export async function sendMsg(core: NapCatCore, peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], waitComplete = true) {
const NTQQMsgApi = coreContext.apis.MsgApi; const NTQQMsgApi = core.apis.MsgApi;
const logger = coreContext.context.logger; const logger = core.context.logger;
if (!sendElements.length) { if (!sendElements.length) {
throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型'); throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型');
} }
@@ -80,13 +80,13 @@ export async function sendMsg(coreContext: NapCatCore, peer: Peer, sendElements:
return returnMsg; return returnMsg;
} }
async function createContext(coreContext: NapCatCore, payload: OB11PostSendMsg, contextMode: ContextMode): Promise<Peer> { async function createContext(core: NapCatCore, payload: OB11PostSendMsg, contextMode: ContextMode): Promise<Peer> {
// This function determines the type of message by the existence of user_id / group_id, // This function determines the type of message by the existence of user_id / group_id,
// not message_type. // not message_type.
// This redundant design of Ob11 here should be blamed. // This redundant design of Ob11 here should be blamed.
const NTQQFriendApi = coreContext.apis.FriendApi; const NTQQFriendApi = core.apis.FriendApi;
const NTQQUserApi = coreContext.apis.UserApi; const NTQQUserApi = core.apis.UserApi;
const NTQQMsgApi = coreContext.apis.MsgApi; const NTQQMsgApi = core.apis.MsgApi;
if ((contextMode === ContextMode.Group || contextMode === ContextMode.Normal) && payload.group_id) { if ((contextMode === ContextMode.Group || contextMode === ContextMode.Normal) && payload.group_id) {
return { return {
chatType: ChatType.KCHATTYPEGROUP, chatType: ChatType.KCHATTYPEGROUP,
@@ -149,7 +149,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
}; };
} }
if (payload.user_id && payload.message_type !== 'group') { if (payload.user_id && payload.message_type !== 'group') {
// const uid = await this.CoreContext.apis.UserApi.getUidByUinV2(payload.user_id.toString()); // const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
// const isBuddy = await NTQQFriendApi.isBuddy(uid!); // const isBuddy = await NTQQFriendApi.isBuddy(uid!);
// if (!isBuddy) { } // if (!isBuddy) { }
} }
@@ -159,7 +159,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
async _handle(payload: OB11PostSendMsg): Promise<{ message_id: number }> { async _handle(payload: OB11PostSendMsg): Promise<{ message_id: number }> {
if (payload.message_type === 'group') this.contextMode = ContextMode.Group; if (payload.message_type === 'group') this.contextMode = ContextMode.Group;
if (payload.message_type === 'private') this.contextMode = ContextMode.Private; if (payload.message_type === 'private') this.contextMode = ContextMode.Private;
const peer = await createContext(this.CoreContext, payload, this.contextMode); const peer = await createContext(this.core, payload, this.contextMode);
const messages = normalize( const messages = normalize(
payload.message, payload.message,
@@ -187,20 +187,20 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
} }
// log("send msg:", peer, sendElements) // log("send msg:", peer, sendElements)
const { sendElements, deleteAfterSentFiles } = await this.OneBotContext.apiContext.MsgApi const { sendElements, deleteAfterSentFiles } = await this.obContext.apiContext.MsgApi
.createSendElements(messages, peer); .createSendElements(messages, peer);
const returnMsg = await sendMsg(this.CoreContext, peer, sendElements, deleteAfterSentFiles); const returnMsg = await sendMsg(this.core, peer, sendElements, deleteAfterSentFiles);
return { message_id: returnMsg!.id! }; return { message_id: returnMsg!.id! };
} }
private async handleForwardedNodes(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<RawMessage | null> { private async handleForwardedNodes(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<RawMessage | null> {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const selfPeer = { const selfPeer = {
chatType: ChatType.KCHATTYPEC2C, chatType: ChatType.KCHATTYPEC2C,
peerUid: this.CoreContext.selfInfo.uid, peerUid: this.core.selfInfo.uid,
}; };
let nodeMsgIds: string[] = []; let nodeMsgIds: string[] = [];
const logger = this.CoreContext.context.logger; const logger = this.core.context.logger;
for (const messageNode of messageNodes) { for (const messageNode of messageNodes) {
const nodeId = messageNode.data.id; const nodeId = messageNode.data.id;
if (nodeId) { if (nodeId) {
@@ -230,7 +230,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
//完成子卡片生成跳过后续 //完成子卡片生成跳过后续
continue; continue;
} }
const { sendElements } = await this.OneBotContext.apiContext.MsgApi const { sendElements } = await this.obContext.apiContext.MsgApi
.createSendElements(OB11Data, destPeer); .createSendElements(OB11Data, destPeer);
//拆分消息 //拆分消息
const MixElement = sendElements.filter(element => element.elementType !== ElementType.FILE && element.elementType !== ElementType.VIDEO); const MixElement = sendElements.filter(element => element.elementType !== ElementType.FILE && element.elementType !== ElementType.VIDEO);
@@ -238,7 +238,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
const AllElement: SendMessageElement[][] = [MixElement, ...SingleElement].filter(e => e !== undefined && e.length !== 0); const AllElement: SendMessageElement[][] = [MixElement, ...SingleElement].filter(e => e !== undefined && e.length !== 0);
const MsgNodeList: Promise<RawMessage | undefined>[] = []; const MsgNodeList: Promise<RawMessage | undefined>[] = [];
for (const sendElementsSplitElement of AllElement) { for (const sendElementsSplitElement of AllElement) {
MsgNodeList.push(sendMsg(this.CoreContext, selfPeer, sendElementsSplitElement, [], true).catch(_ => undefined)); MsgNodeList.push(sendMsg(this.core, selfPeer, sendElementsSplitElement, [], true).catch(_ => undefined));
} }
(await Promise.allSettled(MsgNodeList)).map((result) => { (await Promise.allSettled(MsgNodeList)).map((result) => {
if (result.status === 'fulfilled' && result.value) { if (result.status === 'fulfilled' && result.value) {
@@ -272,7 +272,7 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
let retMsgIds: string[] = []; let retMsgIds: string[] = [];
if (needSendSelf) { if (needSendSelf) {
for (const [, msg] of nodeMsgArray.entries()) { for (const [, msg] of nodeMsgArray.entries()) {
if (msg.peerUid === this.CoreContext.selfInfo.uid) { if (msg.peerUid === this.core.selfInfo.uid) {
retMsgIds.push(msg.msgId); retMsgIds.push(msg.msgId);
continue; continue;
} }
@@ -295,10 +295,10 @@ export class SendMsg extends BaseAction<OB11PostSendMsg, ReturnDataType> {
async cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> { async cloneMsg(msg: RawMessage): Promise<RawMessage | undefined> {
const selfPeer = { const selfPeer = {
chatType: ChatType.KCHATTYPEC2C, chatType: ChatType.KCHATTYPEC2C,
peerUid: this.CoreContext.selfInfo.uid, peerUid: this.core.selfInfo.uid,
}; };
const logger = this.CoreContext.context.logger; const logger = this.core.context.logger;
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
//msg 为待克隆消息 //msg 为待克隆消息
const sendElements: SendMessageElement[] = []; const sendElements: SendMessageElement[] = [];

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
export class SetMsgEmojiLike extends BaseAction<Payload, any> { export class SetMsgEmojiLike extends BaseAction<Payload, any> {
actionName = ActionName.SetMsgEmojiLike; actionName = ActionName.SetMsgEmojiLike;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString())); const msg = MessageUnique.getMsgIdAndPeerByShortId(parseInt(payload.message_id.toString()));
if (!msg) { if (!msg) {
throw new Error('msg not found'); throw new Error('msg not found');

View File

@@ -7,7 +7,7 @@ class GetLoginInfo extends BaseAction<null, OB11User> {
actionName = ActionName.GetLoginInfo; actionName = ActionName.GetLoginInfo;
async _handle(payload: null) { async _handle(payload: null) {
return OB11Constructor.selfInfo(this.CoreContext.selfInfo); return OB11Constructor.selfInfo(this.core.selfInfo);
} }
} }

View File

@@ -6,7 +6,7 @@ export default class GetStatus extends BaseAction<any, any> {
async _handle(payload: any): Promise<any> { async _handle(payload: any): Promise<any> {
return { return {
online: !!this.CoreContext.selfInfo.online, online: !!this.core.selfInfo.online,
good: true, good: true,
stat: {}, stat: {},
}; };

View File

@@ -19,11 +19,11 @@ type Payload = FromSchema<typeof SchemaData>;
export class GetCookies extends BaseAction<Payload, Response> { export class GetCookies extends BaseAction<Payload, Response> {
actionName = ActionName.GetCookies; actionName = ActionName.GetCookies;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQWebApi = this.CoreContext.apis.WebApi; const NTQQWebApi = this.core.apis.WebApi;
// if (!payload.domain) { // if (!payload.domain) {
// throw new Error('缺少参数 domain'); // throw new Error('缺少参数 domain');
// } // }

View File

@@ -15,11 +15,11 @@ const SchemaData = {
type Payload = FromSchema<typeof SchemaData>; type Payload = FromSchema<typeof SchemaData>;
export default class GetFriendList extends BaseAction<Payload, OB11User[]> { export default class GetFriendList extends BaseAction<Payload, OB11User[]> {
actionName = ActionName.GetFriendList; actionName = ActionName.GetFriendList;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
//全新逻辑 //全新逻辑
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
return OB11Constructor.friendsV2(await NTQQFriendApi.getBuddyV2(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache)); return OB11Constructor.friendsV2(await NTQQFriendApi.getBuddyV2(typeof payload.no_cache === 'string' ? payload.no_cache === 'true' : !!payload.no_cache));
} }
} }

View File

@@ -13,17 +13,17 @@ type Payload = FromSchema<typeof SchemaData>;
export default class GetRecentContact extends BaseAction<Payload, any> { export default class GetRecentContact extends BaseAction<Payload, any> {
actionName = ActionName.GetRecentContact; actionName = ActionName.GetRecentContact;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload) { async _handle(payload: Payload) {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQMsgApi = this.CoreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const ret = await NTQQUserApi.getRecentContactListSnapShot(+(payload.count || 10)); const ret = await NTQQUserApi.getRecentContactListSnapShot(+(payload.count || 10));
return await Promise.all(ret.info.changedList.map(async (t) => { return await Promise.all(ret.info.changedList.map(async (t) => {
const FastMsg = await NTQQMsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]); const FastMsg = await NTQQMsgApi.getMsgsByMsgId({ chatType: t.chatType, peerUid: t.peerUid }, [t.msgId]);
if (FastMsg.msgList.length > 0) { if (FastMsg.msgList.length > 0) {
//扩展ret.info.changedList //扩展ret.info.changedList
const lastestMsg = await this.OneBotContext.apiContext.MsgApi.parseMessage(FastMsg.msgList[0], 'array'); const lastestMsg = await this.obContext.apiContext.MsgApi.parseMessage(FastMsg.msgList[0], 'array');
return { return {
lastestMsg: lastestMsg, lastestMsg: lastestMsg,
peerUin: t.peerUin, peerUin: t.peerUin,

View File

@@ -15,10 +15,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SendLike extends BaseAction<Payload, null> { export default class SendLike extends BaseAction<Payload, null> {
actionName = ActionName.SendLike; actionName = ActionName.SendLike;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQUserApi = this.CoreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
//logDebug('点赞参数', payload); //logDebug('点赞参数', payload);
try { try {
const qq = payload.user_id.toString(); const qq = payload.user_id.toString();

View File

@@ -16,10 +16,10 @@ type Payload = FromSchema<typeof SchemaData>;
export default class SetFriendAddRequest extends BaseAction<Payload, null> { export default class SetFriendAddRequest extends BaseAction<Payload, null> {
actionName = ActionName.SetFriendAddRequest; actionName = ActionName.SetFriendAddRequest;
PayloadSchema = SchemaData; payloadSchema = SchemaData;
async _handle(payload: Payload): Promise<null> { async _handle(payload: Payload): Promise<null> {
const NTQQFriendApi = this.CoreContext.apis.FriendApi; const NTQQFriendApi = this.core.apis.FriendApi;
const approve = payload.approve?.toString() !== 'false'; const approve = payload.approve?.toString() !== 'false';
await NTQQFriendApi.handleFriendRequest(payload.flag, approve); await NTQQFriendApi.handleFriendRequest(payload.flag, approve);
return null; return null;

View File

@@ -5,15 +5,15 @@ import { OB11FriendPokeEvent } from '../event/notice/OB11PokeEvent';
export class OneBotFriendApi { export class OneBotFriendApi {
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
coreContext: NapCatCore; core: NapCatCore;
friendList: Map<string, any> = new Map();//此处作为缓存 uin->info friendList: Map<string, any> = new Map();//此处作为缓存 uin->info
constructor(obContext: NapCatOneBot11Adapter, coreContext: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.obContext = obContext; this.obContext = obContext;
this.coreContext = coreContext; this.core = core;
} }
//使用前预先判断 busiId 1061 //使用前预先判断 busiId 1061
async parsePrivatePokeEvent(grayTipElement: GrayTipElement) { async parsePrivatePokeEvent(grayTipElement: GrayTipElement) {
const NTQQUserApi = this.coreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr); const json = JSON.parse(grayTipElement.jsonGrayTipElement.jsonStr);
let pokedetail: any[] = json.items; let pokedetail: any[] = json.items;
//筛选item带有uid的元素 //筛选item带有uid的元素
@@ -21,7 +21,7 @@ export class OneBotFriendApi {
//console.log("[NapCat] 群拍一拍 群:", pokedetail, parseInt(msg.peerUid), " ", await NTQQUserApi.getUinByUid(pokedetail[0].uid), "拍了拍", await NTQQUserApi.getUinByUid(pokedetail[1].uid)); //console.log("[NapCat] 群拍一拍 群:", pokedetail, parseInt(msg.peerUid), " ", await NTQQUserApi.getUinByUid(pokedetail[0].uid), "拍了拍", await NTQQUserApi.getUinByUid(pokedetail[1].uid));
if (pokedetail.length == 2) { if (pokedetail.length == 2) {
return new OB11FriendPokeEvent( return new OB11FriendPokeEvent(
this.coreContext, this.core,
parseInt((await NTQQUserApi.getUinByUidV2(pokedetail[0].uid))!), parseInt((await NTQQUserApi.getUinByUidV2(pokedetail[0].uid))!),
parseInt((await NTQQUserApi.getUinByUidV2(pokedetail[1].uid))!), parseInt((await NTQQUserApi.getUinByUidV2(pokedetail[1].uid))!),
pokedetail pokedetail

View File

@@ -9,15 +9,15 @@ import { MessageUnique } from '@/common/utils/MessageUnique';
export class OneBotGroupApi { export class OneBotGroupApi {
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
coreContext: NapCatCore; core: NapCatCore;
GroupMemberList: Map<string, any> = new Map();//此处作为缓存 group_id->memberUin->info GroupMemberList: Map<string, any> = new Map();//此处作为缓存 group_id->memberUin->info
constructor(obContext: NapCatOneBot11Adapter, coreContext: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.obContext = obContext; this.obContext = obContext;
this.coreContext = coreContext; this.core = core;
} }
async parseGroupBanEvent(GroupCode: string, grayTipElement: GrayTipElement) { async parseGroupBanEvent(GroupCode: string, grayTipElement: GrayTipElement) {
const groupElement = grayTipElement?.groupElement; const groupElement = grayTipElement?.groupElement;
const NTQQGroupApi = this.coreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
if (!groupElement?.shutUp) return undefined; if (!groupElement?.shutUp) return undefined;
const memberUid = groupElement.shutUp!.member.uid; const memberUid = groupElement.shutUp!.member.uid;
const adminUid = groupElement.shutUp!.admin.uid; const adminUid = groupElement.shutUp!.admin.uid;
@@ -35,7 +35,7 @@ export class OneBotGroupApi {
const adminUin = (await NTQQGroupApi.getGroupMember(GroupCode, adminUid))?.uin; const adminUin = (await NTQQGroupApi.getGroupMember(GroupCode, adminUid))?.uin;
if (memberUin && adminUin) { if (memberUin && adminUin) {
return new OB11GroupBanEvent( return new OB11GroupBanEvent(
this.coreContext, this.core,
parseInt(GroupCode), parseInt(GroupCode),
parseInt(memberUin), parseInt(memberUin),
parseInt(adminUin), parseInt(adminUin),
@@ -46,7 +46,7 @@ export class OneBotGroupApi {
return undefined; return undefined;
} }
async parseGroupIncreaseEvent(GroupCode: string, grayTipElement: GrayTipElement) { async parseGroupIncreaseEvent(GroupCode: string, grayTipElement: GrayTipElement) {
this.coreContext.context.logger.logDebug('收到新人被邀请进群消息', grayTipElement); this.core.context.logger.logDebug('收到新人被邀请进群消息', grayTipElement);
const xmlElement = grayTipElement.xmlElement; const xmlElement = grayTipElement.xmlElement;
if (xmlElement?.content) { if (xmlElement?.content) {
const regex = /jp="(\d+)"/g; const regex = /jp="(\d+)"/g;
@@ -61,7 +61,7 @@ export class OneBotGroupApi {
if (matches.length === 2) { if (matches.length === 2) {
const [inviter, invitee] = matches; const [inviter, invitee] = matches;
return new OB11GroupIncreaseEvent( return new OB11GroupIncreaseEvent(
this.coreContext, this.core,
parseInt(GroupCode), parseInt(GroupCode),
parseInt(invitee), parseInt(invitee),
parseInt(inviter), parseInt(inviter),
@@ -72,7 +72,7 @@ export class OneBotGroupApi {
return undefined; return undefined;
} }
async parseGroupMemberIncreaseEvent(GroupCode: string, grayTipElement: GrayTipElement) { async parseGroupMemberIncreaseEvent(GroupCode: string, grayTipElement: GrayTipElement) {
const NTQQGroupApi = this.coreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const groupElement = grayTipElement?.groupElement; const groupElement = grayTipElement?.groupElement;
if (!groupElement) return undefined; if (!groupElement) return undefined;
const member = await NTQQGroupApi.getGroupMemberV2(GroupCode, groupElement.memberUid); const member = await NTQQGroupApi.getGroupMemberV2(GroupCode, groupElement.memberUid);
@@ -81,7 +81,7 @@ export class OneBotGroupApi {
if (memberUin) { if (memberUin) {
const operatorUin = adminMember?.uin || memberUin; const operatorUin = adminMember?.uin || memberUin;
return new OB11GroupIncreaseEvent( return new OB11GroupIncreaseEvent(
this.coreContext, this.core,
parseInt(GroupCode), parseInt(GroupCode),
parseInt(memberUin), parseInt(memberUin),
parseInt(operatorUin) parseInt(operatorUin)
@@ -90,16 +90,16 @@ export class OneBotGroupApi {
return undefined; return undefined;
} }
async parseGroupKickEvent(GroupCode: string, grayTipElement: GrayTipElement) { async parseGroupKickEvent(GroupCode: string, grayTipElement: GrayTipElement) {
const NTQQGroupApi = this.coreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.coreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const groupElement = grayTipElement?.groupElement; const groupElement = grayTipElement?.groupElement;
if (!groupElement) return undefined; if (!groupElement) return undefined;
const adminUin = (await NTQQGroupApi.getGroupMember(GroupCode, groupElement.adminUid))?.uin || (await NTQQUserApi.getUidByUinV2(groupElement.adminUid)); const adminUin = (await NTQQGroupApi.getGroupMember(GroupCode, groupElement.adminUid))?.uin || (await NTQQUserApi.getUidByUinV2(groupElement.adminUid));
if (adminUin) { if (adminUin) {
return new OB11GroupDecreaseEvent( return new OB11GroupDecreaseEvent(
this.coreContext, this.core,
parseInt(GroupCode), parseInt(GroupCode),
parseInt(this.coreContext.selfInfo.uin), parseInt(this.core.selfInfo.uin),
parseInt(adminUin), parseInt(adminUin),
'kick_me' 'kick_me'
); );
@@ -107,12 +107,12 @@ export class OneBotGroupApi {
return undefined; return undefined;
} }
async parseGroupEmjioLikeEvent(GroupCode: string, grayTipElement: GrayTipElement) { async parseGroupEmjioLikeEvent(GroupCode: string, grayTipElement: GrayTipElement) {
const NTQQMsgApi = this.coreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const emojiLikeData = new fastXmlParser.XMLParser({ const emojiLikeData = new fastXmlParser.XMLParser({
ignoreAttributes: false, ignoreAttributes: false,
attributeNamePrefix: '', attributeNamePrefix: '',
}).parse(grayTipElement.xmlElement.content); }).parse(grayTipElement.xmlElement.content);
this.coreContext.context.logger.logDebug('收到表情回应我的消息', emojiLikeData); this.core.context.logger.logDebug('收到表情回应我的消息', emojiLikeData);
try { try {
const senderUin = emojiLikeData.gtip.qq.jp; const senderUin = emojiLikeData.gtip.qq.jp;
const msgSeq = emojiLikeData.gtip.url.msgseq; const msgSeq = emojiLikeData.gtip.url.msgseq;
@@ -130,7 +130,7 @@ export class OneBotGroupApi {
//console.log("表情回应消息长度检测", msgSeq, replyMsg.elements); //console.log("表情回应消息长度检测", msgSeq, replyMsg.elements);
if (!replyMsg) throw new Error('找不到回应消息'); if (!replyMsg) throw new Error('找不到回应消息');
return new OB11GroupMsgEmojiLikeEvent( return new OB11GroupMsgEmojiLikeEvent(
this.coreContext, this.core,
parseInt(GroupCode), parseInt(GroupCode),
parseInt(senderUin), parseInt(senderUin),
MessageUnique.getShortIdByMsgId(replyMsg.msgId)!, MessageUnique.getShortIdByMsgId(replyMsg.msgId)!,
@@ -140,7 +140,7 @@ export class OneBotGroupApi {
}], }],
); );
} catch (e: any) { } catch (e: any) {
this.coreContext.context.logger.logError('解析表情回应消息失败', e.stack); this.core.context.logger.logError('解析表情回应消息失败', e.stack);
} }
return undefined; return undefined;
} }

View File

@@ -55,7 +55,7 @@ function keyCanBeParsed(key: string, parser: RawToOb11Converters): key is keyof
export class OneBotMsgApi { export class OneBotMsgApi {
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
coreContext: NapCatCore; core: NapCatCore;
rawToOb11Converters: RawToOb11Converters = { rawToOb11Converters: RawToOb11Converters = {
textElement: async element => { textElement: async element => {
@@ -78,7 +78,7 @@ export class OneBotMsgApi {
const { atNtUid, /* content */ } = element; const { atNtUid, /* content */ } = element;
let atQQ = element.atUid; let atQQ = element.atUid;
if (!atQQ || atQQ === '0') { if (!atQQ || atQQ === '0') {
atQQ = await this.coreContext.apis.UserApi.getUinByUidV2(atNtUid); atQQ = await this.core.apis.UserApi.getUinByUidV2(atNtUid);
} }
if (atQQ) { if (atQQ) {
qq = atQQ as `${number}`; qq = atQQ as `${number}`;
@@ -102,18 +102,18 @@ export class OneBotMsgApi {
file: element.fileName, file: element.fileName,
sub_type: element.picSubType, sub_type: element.picSubType,
file_id: UUIDConverter.encode(msg.peerUin, msg.msgId), file_id: UUIDConverter.encode(msg.peerUin, msg.msgId),
url: await this.coreContext.apis.FileApi.getImageUrl(element), url: await this.core.apis.FileApi.getImageUrl(element),
file_size: element.fileSize, file_size: element.fileSize,
}, },
}; };
} catch (e: any) { } catch (e: any) {
this.coreContext.context.logger.logError('获取图片url失败', e.stack); this.core.context.logger.logError('获取图片url失败', e.stack);
return null; return null;
} }
}, },
fileElement: async (element, msg, elementWrapper) => { fileElement: async (element, msg, elementWrapper) => {
await this.coreContext.apis.FileApi.addFileCache( await this.core.apis.FileApi.addFileCache(
{ {
peerUid: msg.peerUid, peerUid: msg.peerUid,
chatType: msg.chatType, chatType: msg.chatType,
@@ -166,7 +166,7 @@ export class OneBotMsgApi {
}, },
marketFaceElement: async (_, msg, elementWrapper) => { marketFaceElement: async (_, msg, elementWrapper) => {
await this.coreContext.apis.FileApi.addFileCache( await this.core.apis.FileApi.addFileCache(
{ {
peerUid: msg.peerUid, peerUid: msg.peerUid,
chatType: msg.chatType, chatType: msg.chatType,
@@ -192,7 +192,7 @@ export class OneBotMsgApi {
}, },
replyElement: async (element, msg) => { replyElement: async (element, msg) => {
const NTQQMsgApi = this.coreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords); const records = msg.records.find(msgRecord => msgRecord.msgId === element?.sourceMsgIdInRecords);
const peer = { const peer = {
chatType: msg.chatType, chatType: msg.chatType,
@@ -200,7 +200,7 @@ export class OneBotMsgApi {
guildId: '', guildId: '',
}; };
if (!records) { if (!records) {
this.coreContext.context.logger.logError('获取不到引用的消息', element.replayMsgSeq); this.core.context.logger.logError('获取不到引用的消息', element.replayMsgSeq);
return null; return null;
} }
let replyMsg: RawMessage | undefined; let replyMsg: RawMessage | undefined;
@@ -221,7 +221,7 @@ export class OneBotMsgApi {
// Attempt 3 // Attempt 3
const replyMsgList = (await NTQQMsgApi.getMsgExBySeq(peer, records.msgSeq)).msgList; const replyMsgList = (await NTQQMsgApi.getMsgExBySeq(peer, records.msgSeq)).msgList;
if (replyMsgList.length < 1) { if (replyMsgList.length < 1) {
this.coreContext.context.logger.logError('回复消息消息验证失败', element.replayMsgSeq); this.core.context.logger.logError('回复消息消息验证失败', element.replayMsgSeq);
return null; return null;
} }
replyMsg = replyMsgList.filter(e => e.msgSeq == records.msgSeq) replyMsg = replyMsgList.filter(e => e.msgSeq == records.msgSeq)
@@ -242,7 +242,7 @@ export class OneBotMsgApi {
}, },
videoElement: async (element, msg, elementWrapper) => { videoElement: async (element, msg, elementWrapper) => {
const NTQQFileApi = this.coreContext.apis.FileApi; const NTQQFileApi = this.core.apis.FileApi;
//读取视频链接并兜底 //读取视频链接并兜底
let videoUrlWrappers: Awaited<ReturnType<typeof NTQQFileApi.getVideoUrl>> | undefined; let videoUrlWrappers: Awaited<ReturnType<typeof NTQQFileApi.getVideoUrl>> | undefined;
@@ -257,7 +257,7 @@ export class OneBotMsgApi {
guildId: '0', guildId: '0',
}, msg.msgId, elementWrapper.elementId); }, msg.msgId, elementWrapper.elementId);
} catch (error) { } catch (error) {
this.coreContext.context.logger.logWarn('获取视频 URL 失败'); this.core.context.logger.logWarn('获取视频 URL 失败');
} }
//读取在线URL //读取在线URL
@@ -305,7 +305,7 @@ export class OneBotMsgApi {
}, },
pttElement: async (element, msg, elementWrapper) => { pttElement: async (element, msg, elementWrapper) => {
await this.coreContext.apis.FileApi.addFileCache( await this.core.apis.FileApi.addFileCache(
{ {
peerUid: msg.peerUid, peerUid: msg.peerUid,
chatType: msg.chatType, chatType: msg.chatType,
@@ -331,7 +331,7 @@ export class OneBotMsgApi {
}, },
multiForwardMsgElement: async (_, msg) => { multiForwardMsgElement: async (_, msg) => {
const NTQQMsgApi = this.coreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const message_data: OB11MessageForward = { const message_data: OB11MessageForward = {
data: {} as any, data: {} as any,
type: OB11MessageDataType.forward, type: OB11MessageDataType.forward,
@@ -418,8 +418,8 @@ export class OneBotMsgApi {
if (!context.peer || context.peer.chatType == ChatType.KCHATTYPEC2C) return undefined; if (!context.peer || context.peer.chatType == ChatType.KCHATTYPEC2C) return undefined;
if (atQQ === 'all') return at(atQQ, atQQ, AtType.atAll, '全体成员'); if (atQQ === 'all') return at(atQQ, atQQ, AtType.atAll, '全体成员');
const NTQQGroupApi = this.coreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.coreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const atMember = await NTQQGroupApi.getGroupMember(context.peer.peerUid, atQQ); const atMember = await NTQQGroupApi.getGroupMember(context.peer.peerUid, atQQ);
if (atMember) { if (atMember) {
return at(atQQ, atMember.uid, AtType.atUser, atMember.nick || atMember.cardName); return at(atQQ, atMember.uid, AtType.atUser, atMember.nick || atMember.cardName);
@@ -433,10 +433,10 @@ export class OneBotMsgApi {
[OB11MessageDataType.reply]: async ({ data: { id } }) => { [OB11MessageDataType.reply]: async ({ data: { id } }) => {
const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id)); const replyMsgM = MessageUnique.getMsgIdAndPeerByShortId(parseInt(id));
if (!replyMsgM) { if (!replyMsgM) {
this.coreContext.context.logger.logWarn('回复消息不存在', id); this.core.context.logger.logWarn('回复消息不存在', id);
return undefined; return undefined;
} }
const NTQQMsgApi = this.coreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const replyMsg = (await NTQQMsgApi.getMsgsByMsgId( const replyMsg = (await NTQQMsgApi.getMsgsByMsgId(
replyMsgM.Peer, [replyMsgM.MsgId])).msgList[0]; replyMsgM.Peer, [replyMsgM.MsgId])).msgList[0];
return replyMsg ? return replyMsg ?
@@ -497,7 +497,7 @@ export class OneBotMsgApi {
// File service // File service
[OB11MessageDataType.image]: async (sendMsg, context) => { [OB11MessageDataType.image]: async (sendMsg, context) => {
const sendPicElement = await this.coreContext.apis.FileApi.createValidSendPicElement( const sendPicElement = await this.core.apis.FileApi.createValidSendPicElement(
(await this.handleOb11FileLikeMessage(sendMsg, context)).path, (await this.handleOb11FileLikeMessage(sendMsg, context)).path,
sendMsg.data.summary, sendMsg.data.summary,
sendMsg.data.sub_type, sendMsg.data.sub_type,
@@ -508,7 +508,7 @@ export class OneBotMsgApi {
[OB11MessageDataType.file]: async (sendMsg, context) => { [OB11MessageDataType.file]: async (sendMsg, context) => {
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context); const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
return await this.coreContext.apis.FileApi.createValidSendFileElement(path, fileName); return await this.core.apis.FileApi.createValidSendFileElement(path, fileName);
}, },
[OB11MessageDataType.video]: async (sendMsg, context) => { [OB11MessageDataType.video]: async (sendMsg, context) => {
@@ -516,17 +516,17 @@ export class OneBotMsgApi {
let thumb = sendMsg.data.thumb; let thumb = sendMsg.data.thumb;
if (thumb) { if (thumb) {
const uri2LocalRes = await uri2local(this.coreContext.NapCatTempPath, thumb); const uri2LocalRes = await uri2local(this.core.NapCatTempPath, thumb);
if (uri2LocalRes.success) thumb = uri2LocalRes.path; if (uri2LocalRes.success) thumb = uri2LocalRes.path;
} }
const videoEle = await this.coreContext.apis.FileApi.createValidSendVideoElement(path, fileName, thumb); const videoEle = await this.core.apis.FileApi.createValidSendVideoElement(path, fileName, thumb);
context.deleteAfterSentFiles.push(videoEle.videoElement.filePath); context.deleteAfterSentFiles.push(videoEle.videoElement.filePath);
return videoEle; return videoEle;
}, },
[OB11MessageDataType.voice]: async (sendMsg, context) => [OB11MessageDataType.voice]: async (sendMsg, context) =>
this.coreContext.apis.FileApi.createValidSendPttElement( this.core.apis.FileApi.createValidSendPttElement(
(await this.handleOb11FileLikeMessage(sendMsg, context)).path), (await this.handleOb11FileLikeMessage(sendMsg, context)).path),
[OB11MessageDataType.json]: async ({ data: { data } }) => ({ [OB11MessageDataType.json]: async ({ data: { data } }) => ({
@@ -584,24 +584,24 @@ export class OneBotMsgApi {
// 保留, 直到...找到更好的解决方案 // 保留, 直到...找到更好的解决方案
if (data.type === 'custom') { if (data.type === 'custom') {
if (!data.url) { if (!data.url) {
this.coreContext.context.logger.logError('自定义音卡缺少参数url'); this.core.context.logger.logError('自定义音卡缺少参数url');
return undefined; return undefined;
} }
if (!data.audio) { if (!data.audio) {
this.coreContext.context.logger.logError('自定义音卡缺少参数audio'); this.core.context.logger.logError('自定义音卡缺少参数audio');
return undefined; return undefined;
} }
if (!data.title) { if (!data.title) {
this.coreContext.context.logger.logError('自定义音卡缺少参数title'); this.core.context.logger.logError('自定义音卡缺少参数title');
return undefined; return undefined;
} }
} else { } else {
if (!['qq', '163'].includes(data.type)) { if (!['qq', '163'].includes(data.type)) {
this.coreContext.context.logger.logError('音乐卡片type错误, 只支持qq、163、custom当前type:', data.type); this.core.context.logger.logError('音乐卡片type错误, 只支持qq、163、custom当前type:', data.type);
return undefined; return undefined;
} }
if (!data.id) { if (!data.id) {
this.coreContext.context.logger.logError('音乐卡片缺少参数id'); this.core.context.logger.logError('音乐卡片缺少参数id');
return undefined; return undefined;
} }
} }
@@ -621,7 +621,7 @@ export class OneBotMsgApi {
const musicJson = await RequestUtil.HttpGetJson<any>(signUrl, 'POST', postData); const musicJson = await RequestUtil.HttpGetJson<any>(signUrl, 'POST', postData);
return this.ob11ToRawConverters.json(musicJson, context); return this.ob11ToRawConverters.json(musicJson, context);
} catch (e) { } catch (e) {
this.coreContext.context.logger.logError('生成音乐消息失败', e); this.core.context.logger.logError('生成音乐消息失败', e);
} }
}, },
@@ -645,9 +645,9 @@ export class OneBotMsgApi {
[OB11MessageDataType.miniapp]: async () => undefined, [OB11MessageDataType.miniapp]: async () => undefined,
}; };
constructor(obContext: NapCatOneBot11Adapter, coreContext: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.obContext = obContext; this.obContext = obContext;
this.coreContext = coreContext; this.core = core;
} }
async parseMessage( async parseMessage(
@@ -657,11 +657,11 @@ export class OneBotMsgApi {
if (msg.senderUin == '0' || msg.senderUin == '') return; if (msg.senderUin == '0' || msg.senderUin == '') return;
if (msg.peerUin == '0' || msg.peerUin == '') return; if (msg.peerUin == '0' || msg.peerUin == '') return;
//跳过空消息 //跳过空消息
const NTQQGroupApi = this.coreContext.apis.GroupApi; const NTQQGroupApi = this.core.apis.GroupApi;
const NTQQUserApi = this.coreContext.apis.UserApi; const NTQQUserApi = this.core.apis.UserApi;
const NTQQMsgApi = this.coreContext.apis.MsgApi; const NTQQMsgApi = this.core.apis.MsgApi;
const resMsg: OB11Message = { const resMsg: OB11Message = {
self_id: parseInt(this.coreContext.selfInfo.uin), self_id: parseInt(this.core.selfInfo.uin),
user_id: parseInt(msg.senderUin!), user_id: parseInt(msg.senderUin!),
time: parseInt(msg.msgTime) || Date.now(), time: parseInt(msg.msgTime) || Date.now(),
message_id: msg.id!, message_id: msg.id!,
@@ -678,7 +678,7 @@ export class OneBotMsgApi {
sub_type: 'friend', sub_type: 'friend',
message: messagePostFormat === 'string' ? '' : [], message: messagePostFormat === 'string' ? '' : [],
message_format: messagePostFormat === 'string' ? 'string' : 'array', message_format: messagePostFormat === 'string' ? 'string' : 'array',
post_type: this.coreContext.selfInfo.uin == msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE, post_type: this.core.selfInfo.uin == msg.senderUin ? EventType.MESSAGE_SENT : EventType.MESSAGE,
}; };
if (msg.chatType == ChatType.KCHATTYPEGROUP) { if (msg.chatType == ChatType.KCHATTYPEGROUP) {
resMsg.sub_type = 'normal'; // 这里go-cqhttp是group而onebot11标准是normal, 蛋疼 resMsg.sub_type = 'normal'; // 这里go-cqhttp是group而onebot11标准是normal, 蛋疼
@@ -763,7 +763,7 @@ export class OneBotMsgApi {
const isBlankUrl = !inputdata.url || inputdata.url === ''; const isBlankUrl = !inputdata.url || inputdata.url === '';
const isBlankFile = !inputdata.file || inputdata.file === ''; const isBlankFile = !inputdata.file || inputdata.file === '';
if (isBlankUrl && isBlankFile) { if (isBlankUrl && isBlankFile) {
this.coreContext.context.logger.logError('文件消息缺少参数', inputdata); this.core.context.logger.logError('文件消息缺少参数', inputdata);
throw Error('文件消息缺少参数'); throw Error('文件消息缺少参数');
} }
const fileOrUrl = (isBlankUrl ? inputdata.file : inputdata.url) ?? ""; const fileOrUrl = (isBlankUrl ? inputdata.file : inputdata.url) ?? "";
@@ -773,10 +773,10 @@ export class OneBotMsgApi {
fileName, fileName,
errMsg, errMsg,
success, success,
} = (await uri2local(this.coreContext.NapCatTempPath, fileOrUrl)); } = (await uri2local(this.core.NapCatTempPath, fileOrUrl));
if (!success) { if (!success) {
this.coreContext.context.logger.logError('文件下载失败', errMsg); this.core.context.logger.logError('文件下载失败', errMsg);
throw Error('文件下载失败' + errMsg); throw Error('文件下载失败' + errMsg);
} }

View File

@@ -4,10 +4,10 @@ import { NapCatOneBot11Adapter } from '@/onebot';
export class OneBotUserApi { export class OneBotUserApi {
obContext: NapCatOneBot11Adapter; obContext: NapCatOneBot11Adapter;
coreContext: NapCatCore; core: NapCatCore;
constructor(obContext: NapCatOneBot11Adapter, coreContext: NapCatCore) { constructor(obContext: NapCatOneBot11Adapter, core: NapCatCore) {
this.obContext = obContext; this.obContext = obContext;
this.coreContext = coreContext; this.core = core;
} }
} }

View File

@@ -5,7 +5,7 @@ import { NapCatCore } from '@/core';
export type OB11Config = typeof ob11DefaultConfig; export type OB11Config = typeof ob11DefaultConfig;
export class OB11ConfigLoader extends ConfigBase<OB11Config> { export class OB11ConfigLoader extends ConfigBase<OB11Config> {
constructor(coreContext: NapCatCore, configPath: string) { constructor(core: NapCatCore, configPath: string) {
super('onebot11', coreContext, configPath); super('onebot11', core, configPath);
} }
} }

View File

@@ -16,12 +16,12 @@ import { isNull } from '@/common/utils/helper';
import { normalize, sendMsg } from '../action/msg/SendMsg'; import { normalize, sendMsg } from '../action/msg/SendMsg';
import { NapCatOneBot11Adapter } from '..'; import { NapCatOneBot11Adapter } from '..';
async function handleMsg(coreContext: NapCatCore, obContext: NapCatOneBot11Adapter, msg: OB11Message, quickAction: QuickAction) { async function handleMsg(core: NapCatCore, obContext: NapCatOneBot11Adapter, msg: OB11Message, quickAction: QuickAction) {
msg = msg as OB11Message; msg = msg as OB11Message;
const reply = quickAction.reply; const reply = quickAction.reply;
const peer: Peer = { const peer: Peer = {
chatType: ChatType.KCHATTYPEC2C, chatType: ChatType.KCHATTYPEC2C,
peerUid: await coreContext.apis.UserApi.getUidByUinV2(msg.user_id.toString()) as string, peerUid: await core.apis.UserApi.getUidByUinV2(msg.user_id.toString()) as string,
}; };
if (msg.message_type == 'private') { if (msg.message_type == 'private') {
if (msg.sub_type === 'group') { if (msg.sub_type === 'group') {
@@ -36,7 +36,7 @@ async function handleMsg(coreContext: NapCatCore, obContext: NapCatOneBot11Adapt
let replyMessage: OB11MessageData[] = []; let replyMessage: OB11MessageData[] = [];
if (msg.message_type == 'group') { if (msg.message_type == 'group') {
group = await coreContext.apis.GroupApi.getGroup(msg.group_id!.toString()); group = await core.apis.GroupApi.getGroup(msg.group_id!.toString());
replyMessage.push({ replyMessage.push({
type: 'reply', type: 'reply',
data: { data: {
@@ -54,37 +54,37 @@ async function handleMsg(coreContext: NapCatCore, obContext: NapCatOneBot11Adapt
} }
replyMessage = replyMessage.concat(normalize(reply, quickAction.auto_escape)); replyMessage = replyMessage.concat(normalize(reply, quickAction.auto_escape));
const { sendElements, deleteAfterSentFiles } = await obContext.apiContext.MsgApi.createSendElements(replyMessage, peer); const { sendElements, deleteAfterSentFiles } = await obContext.apiContext.MsgApi.createSendElements(replyMessage, peer);
sendMsg(coreContext, peer, sendElements, deleteAfterSentFiles, false).then().catch(coreContext.context.logger.logError); sendMsg(core, peer, sendElements, deleteAfterSentFiles, false).then().catch(core.context.logger.logError);
} }
} }
async function handleGroupRequest(coreContext: NapCatCore, request: OB11GroupRequestEvent, quickAction: QuickActionGroupRequest) { async function handleGroupRequest(core: NapCatCore, request: OB11GroupRequestEvent, quickAction: QuickActionGroupRequest) {
if (!isNull(quickAction.approve)) { if (!isNull(quickAction.approve)) {
coreContext.apis.GroupApi.handleGroupRequest( core.apis.GroupApi.handleGroupRequest(
request.flag, request.flag,
quickAction.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject, quickAction.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
quickAction.reason, quickAction.reason,
).then().catch(coreContext.context.logger.logError); ).then().catch(core.context.logger.logError);
} }
} }
async function handleFriendRequest(coreContext: NapCatCore, request: OB11FriendRequestEvent, quickAction: QuickActionFriendRequest) { async function handleFriendRequest(core: NapCatCore, request: OB11FriendRequestEvent, quickAction: QuickActionFriendRequest) {
if (!isNull(quickAction.approve)) { if (!isNull(quickAction.approve)) {
coreContext.apis.FriendApi.handleFriendRequest(request.flag, !!quickAction.approve).then().catch(coreContext.context.logger.logError); core.apis.FriendApi.handleFriendRequest(request.flag, !!quickAction.approve).then().catch(core.context.logger.logError);
} }
} }
export async function handleQuickOperation(coreContext: NapCatCore, obContext: NapCatOneBot11Adapter, context: QuickActionEvent, quickAction: QuickAction) { export async function handleQuickOperation(core: NapCatCore, obContext: NapCatOneBot11Adapter, context: QuickActionEvent, quickAction: QuickAction) {
if (context.post_type === 'message') { if (context.post_type === 'message') {
handleMsg(coreContext, obContext, context as OB11Message, quickAction).then().catch(coreContext.context.logger.logError); handleMsg(core, obContext, context as OB11Message, quickAction).then().catch(core.context.logger.logError);
} }
if (context.post_type === 'request') { if (context.post_type === 'request') {
const friendRequest = context as OB11FriendRequestEvent; const friendRequest = context as OB11FriendRequestEvent;
const groupRequest = context as OB11GroupRequestEvent; const groupRequest = context as OB11GroupRequestEvent;
if ((friendRequest).request_type === 'friend') { if ((friendRequest).request_type === 'friend') {
handleFriendRequest(coreContext, friendRequest, quickAction).then().catch(coreContext.context.logger.logError); handleFriendRequest(core, friendRequest, quickAction).then().catch(core.context.logger.logError);
} else if (groupRequest.request_type === 'group') { } else if (groupRequest.request_type === 'group') {
handleGroupRequest(coreContext, groupRequest, quickAction).then().catch(coreContext.context.logger.logError); handleGroupRequest(core, groupRequest, quickAction).then().catch(core.context.logger.logError);
} }
} }
} }

View File

@@ -13,10 +13,10 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
constructor( constructor(
public url: string, public url: string,
public secret: string | undefined, public secret: string | undefined,
public coreContext: NapCatCore, public core: NapCatCore,
public obContext: NapCatOneBot11Adapter public obContext: NapCatOneBot11Adapter
) { ) {
this.logger = coreContext.context.logger; this.logger = core.context.logger;
} }
onEvent<T extends OB11EmitEventContent>(event: T) { onEvent<T extends OB11EmitEventContent>(event: T) {
@@ -25,7 +25,7 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
} }
const headers: Record<string, string> = { const headers: Record<string, string> = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'x-self-id': this.coreContext.selfInfo.uin, 'x-self-id': this.core.selfInfo.uin,
}; };
const msgStr = JSON.stringify(event); const msgStr = JSON.stringify(event);
if (this.secret && this.secret.length > 0) { if (this.secret && this.secret.length > 0) {
@@ -48,7 +48,7 @@ export class OB11ActiveHttpAdapter implements IOB11NetworkAdapter {
return; return;
} }
try { try {
handleQuickOperation(this.coreContext, this.obContext, event as QuickActionEvent, resJson).then().catch(this.logger.logError); handleQuickOperation(this.core, this.obContext, event as QuickActionEvent, resJson).then().catch(this.logger.logError);
} catch (e: any) { } catch (e: any) {
this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报返回快速操作失败', e); this.logger.logError('[OneBot] [Http Client] 新消息事件HTTP上报返回快速操作失败', e);
} }

View File

@@ -19,10 +19,10 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
public reconnectIntervalInMillis: number, public reconnectIntervalInMillis: number,
public heartbeatIntervalInMillis: number, public heartbeatIntervalInMillis: number,
private token: string, private token: string,
public coreContext: NapCatCore, public core: NapCatCore,
public actions: ActionMap, public actions: ActionMap,
) { ) {
this.logger = coreContext.context.logger; this.logger = core.context.logger;
} }
onEvent<T extends OB11EmitEventContent>(event: T) { onEvent<T extends OB11EmitEventContent>(event: T) {
@@ -37,7 +37,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
} }
this.heartbeatRef = setInterval(() => { this.heartbeatRef = setInterval(() => {
if (this.connection && this.connection.readyState === WebSocket.OPEN) { if (this.connection && this.connection.readyState === WebSocket.OPEN) {
this.connection.send(JSON.stringify(new OB11HeartbeatEvent(this.coreContext, this.heartbeatIntervalInMillis, this.coreContext.selfInfo.online, true))); this.connection.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.heartbeatIntervalInMillis, this.core.selfInfo.online, true)));
} }
}, this.heartbeatIntervalInMillis); }, this.heartbeatIntervalInMillis);
await this.tryConnect(); await this.tryConnect();
@@ -74,7 +74,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
handshakeTimeout: 2000, handshakeTimeout: 2000,
perMessageDeflate: false, perMessageDeflate: false,
headers: { headers: {
'X-Self-ID': this.coreContext.selfInfo.uin, 'X-Self-ID': this.core.selfInfo.uin,
'Authorization': `Bearer ${this.token}`, 'Authorization': `Bearer ${this.token}`,
'x-client-role': 'Universal', // koishi-adapter-onebot 需要这个字段 'x-client-role': 'Universal', // koishi-adapter-onebot 需要这个字段
'User-Agent': 'OneBot/11', 'User-Agent': 'OneBot/11',
@@ -89,7 +89,7 @@ export class OB11ActiveWebSocketAdapter implements IOB11NetworkAdapter {
}); });
this.connection.on('open', () => { this.connection.on('open', () => {
try { try {
this.connectEvent(this.coreContext); this.connectEvent(this.core);
} catch (e) { } catch (e) {
this.logger.logError('[OneBot] [WebSocket Client] 发送连接生命周期失败', e); this.logger.logError('[OneBot] [WebSocket Client] 发送连接生命周期失败', e);
} }

View File

@@ -14,7 +14,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
constructor( constructor(
public port: number, public port: number,
public token: string, public token: string,
public coreContext: NapCatCore, public core: NapCatCore,
public actions: ActionMap, public actions: ActionMap,
) { ) {
} }
@@ -26,7 +26,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
open() { open() {
try { try {
if (this.isOpen) { if (this.isOpen) {
this.coreContext.context.logger.logError('Cannot open a closed HTTP server'); this.core.context.logger.logError('Cannot open a closed HTTP server');
return; return;
} }
if (!this.isOpen) { if (!this.isOpen) {
@@ -34,7 +34,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
this.isOpen = true; this.isOpen = true;
} }
} catch (e) { } catch (e) {
this.coreContext.context.logger.logError(`[OneBot] [HTTP Server Adapter] Boot Error: ${e}`); this.core.context.logger.logError(`[OneBot] [HTTP Server Adapter] Boot Error: ${e}`);
} }
} }
@@ -66,7 +66,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
this.app.use((req, res) => this.handleRequest(req, res)); this.app.use((req, res) => this.handleRequest(req, res));
this.server.listen(this.port, () => { this.server.listen(this.port, () => {
this.coreContext.context.logger.log(`[OneBot] [HTTP Server Adapter] Start On Port ${this.port}`); this.core.context.logger.log(`[OneBot] [HTTP Server Adapter] Start On Port ${this.port}`);
}); });
} }
@@ -84,7 +84,7 @@ export class OB11PassiveHttpAdapter implements IOB11NetworkAdapter {
private async handleRequest(req: Request, res: Response) { private async handleRequest(req: Request, res: Response) {
if (!this.isOpen) { if (!this.isOpen) {
this.coreContext.context.logger.log(`[OneBot] [HTTP Server Adapter] Server is closed`); this.core.context.logger.log(`[OneBot] [HTTP Server Adapter] Server is closed`);
return res.json(OB11Response.error('Server is closed', 200)); return res.json(OB11Response.error('Server is closed', 200));
} }

View File

@@ -1,12 +1,10 @@
import { IOB11NetworkAdapter, OB11EmitEventContent } from './index'; import { IOB11NetworkAdapter, OB11EmitEventContent } from './index';
import urlParse from 'url'; import urlParse from 'url';
import BaseAction from '@/onebot/action/BaseAction';
import { WebSocket, WebSocketServer } from 'ws'; import { WebSocket, WebSocketServer } from 'ws';
import { Mutex } from 'async-mutex'; import { Mutex } from 'async-mutex';
import { OB11Response } from '../action/OB11Response'; import { OB11Response } from '../action/OB11Response';
import { ActionName } from '../action/types'; import { ActionName } from '../action/types';
import { NapCatCore } from '@/core'; import { NapCatCore } from '@/core';
import { NapCatOneBot11Adapter } from '..';
import { LogWrapper } from '@/common/utils/log'; import { LogWrapper } from '@/common/utils/log';
import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent'; import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent';
import { IncomingMessage } from 'http'; import { IncomingMessage } from 'http';
@@ -20,7 +18,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
isOpen: boolean = false; isOpen: boolean = false;
hasBeenClosed: boolean = false; hasBeenClosed: boolean = false;
heartbeatInterval: number = 0; heartbeatInterval: number = 0;
coreContext: NapCatCore; core: NapCatCore;
logger: LogWrapper; logger: LogWrapper;
private heartbeatIntervalId: NodeJS.Timeout | null = null; private heartbeatIntervalId: NodeJS.Timeout | null = null;
@@ -29,11 +27,11 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
port: number, port: number,
heartbeatInterval: number, heartbeatInterval: number,
token: string, token: string,
coreContext: NapCatCore, core: NapCatCore,
public actions: ActionMap public actions: ActionMap
) { ) {
this.coreContext = coreContext; this.core = core;
this.logger = coreContext.context.logger; this.logger = core.context.logger;
this.heartbeatInterval = heartbeatInterval; this.heartbeatInterval = heartbeatInterval;
this.wsServer = new WebSocketServer({ this.wsServer = new WebSocketServer({
@@ -41,7 +39,6 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
host: ip, host: ip,
maxPayload: 1024 * 1024 * 1024, maxPayload: 1024 * 1024 * 1024,
}); });
const core = coreContext;
this.wsServer.on('connection', async (wsClient, wsReq) => { this.wsServer.on('connection', async (wsClient, wsReq) => {
if (!this.isOpen) { if (!this.isOpen) {
wsClient.close(); wsClient.close();
@@ -120,7 +117,7 @@ export class OB11PassiveWebSocketAdapter implements IOB11NetworkAdapter {
this.wsClientsMutex.runExclusive(async () => { this.wsClientsMutex.runExclusive(async () => {
this.wsClients.forEach((wsClient) => { this.wsClients.forEach((wsClient) => {
if (wsClient.readyState === WebSocket.OPEN) { if (wsClient.readyState === WebSocket.OPEN) {
wsClient.send(JSON.stringify(new OB11HeartbeatEvent(this.coreContext, this.heartbeatInterval, this.coreContext.selfInfo.online, true))); wsClient.send(JSON.stringify(new OB11HeartbeatEvent(this.core, this.heartbeatInterval, this.core.selfInfo.online, true)));
} }
}); });
}); });