shirosaki-napcatsdk
Version:
全新的,省心的,NapCatQQ SDK
1,093 lines (1,070 loc) • 27.8 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i = decorators.length - 1, decorator; i >= 0; i--)
if (decorator = decorators[i])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result) __defProp(target, key, result);
return result;
};
// src/message/MessageSegment.ts
var MessageSegment = class {
constructor(...params) {
}
};
// src/message/segment/Text.ts
var Text = class _Text extends MessageSegment {
constructor(text) {
super();
this.text = text;
}
toJSON() {
return {
type: "text",
data: {
text: this.text
}
};
}
static fromJSON(obj) {
return new this(obj?.data?.text ?? "");
}
clone() {
return new _Text(this.text);
}
equals(other) {
return this.text === other?.text;
}
};
// src/message/segment/At.ts
var At = class _At extends MessageSegment {
target;
constructor(target) {
super();
this.target = String(target);
}
static fromJSON(obj) {
return new this(obj?.data?.qq ?? 0);
}
toJSON() {
return {
type: "at",
data: {
qq: this.target
}
};
}
clone() {
return new _At(this.target);
}
equals(other) {
return this.target === other?.target;
}
};
// src/message/segment/Reply.ts
var Reply = class _Reply extends MessageSegment {
constructor(id) {
super();
this.id = id;
}
toJSON() {
return {
type: "reply",
data: {
id: this.id
}
};
}
static fromJSON(obj) {
return new this(obj?.data?.id ?? "0");
}
clone() {
return new _Reply(this.id);
}
equals(other) {
return this.id === other?.id;
}
};
// src/message/segment/Face.ts
var Face = class _Face extends MessageSegment {
constructor(id, rawData = {}) {
super();
this.id = id;
this.rawData = rawData;
}
toJSON() {
return {
type: "face",
data: {
...this.rawData,
id: this.id
}
};
}
static fromJSON(json) {
const obj = new this(json?.data?.id ?? "0", json?.data ?? {});
return obj;
}
clone() {
return new _Face(this.id, JSON.parse(JSON.stringify(this.rawData)));
}
equals(other) {
return this.id === other?.id;
}
};
// src/message/segment/Sticker.ts
import { tryCatch } from "@ceale/util";
var Sticker = class _Sticker extends MessageSegment {
constructor(urlOrData, summary) {
super();
this.urlOrData = urlOrData;
this.summary = summary;
}
static fromJSON(json) {
return new this(
json?.data?.url ?? "",
json?.data?.summary ?? void 0
);
}
toJSON() {
const data = Buffer.isBuffer(this.urlOrData) ? "data:application/octet-stream;base64," + this.urlOrData.toString("base64") : this.urlOrData;
return {
type: "image",
data: {
sub_type: 1,
file: data,
summary: this.summary ?? void 0
}
};
}
async getData() {
if (Buffer.isBuffer(this.urlOrData)) {
return this.urlOrData;
} else {
const [data] = await tryCatch((await fetch(this.urlOrData)).arrayBuffer());
if (data) {
return Buffer.from(data);
} else {
return Buffer.alloc(0);
}
}
}
clone() {
return new _Sticker(
Buffer.isBuffer(this.urlOrData) ? Buffer.from(this.urlOrData) : this.urlOrData,
this.summary
);
}
equals(other) {
return this.urlOrData === other?.urlOrData;
}
};
// src/message/segment/Image.ts
import { tryCatch as tryCatch2 } from "@ceale/util";
var Image = class _Image extends MessageSegment {
constructor(urlOrData, summary) {
super();
this.urlOrData = urlOrData;
this.summary = summary;
}
static fromJSON(json) {
return new this(
json?.data?.url ?? "",
json?.data?.summary ?? void 0
);
}
toJSON() {
const data = Buffer.isBuffer(this.urlOrData) ? "data:application/octet-stream;base64," + this.urlOrData.toString("base64") : this.urlOrData;
return {
type: "image",
data: {
file: data,
summary: this.summary ?? void 0
}
};
}
async getData() {
if (Buffer.isBuffer(this.urlOrData)) {
return this.urlOrData;
} else {
const [data] = await tryCatch2((await fetch(this.urlOrData)).arrayBuffer());
if (data) {
return Buffer.from(data);
} else {
return Buffer.alloc(0);
}
}
}
clone() {
return new _Image(
Buffer.isBuffer(this.urlOrData) ? Buffer.from(this.urlOrData) : this.urlOrData,
this.summary
);
}
equals(other) {
return this.urlOrData === other?.urlOrData;
}
};
// src/message/segment/Mface.ts
import { randomBytes } from "node:crypto";
var Mface = class _Mface extends MessageSegment {
constructor(emojiId, emojiPackageId, summary) {
super();
this.emojiId = emojiId;
this.emojiPackageId = emojiPackageId;
this.summary = summary;
}
key = randomBytes(8).toString("hex");
url;
static fromJSON(json) {
const obj = new this(
json?.data?.emoji_package_id ?? "0",
json?.data?.emoji_id ?? "0",
json?.data?.summary ?? void 0
);
obj.key = json?.data?.key ?? obj.key;
obj.url = json?.data?.url ?? obj.url;
return obj;
}
toJSON() {
return {
type: "mface",
data: {
emoji_package_id: this.emojiPackageId,
emoji_id: this.emojiId,
key: this.key,
summary: this.summary ?? void 0
}
};
}
clone() {
const obj = new _Mface(
this.emojiPackageId,
this.emojiId,
this.summary
);
obj.key = this.key;
return obj;
}
equals(other) {
return this.emojiPackageId === other?.emojiPackageId && this.emojiId === other?.emojiId;
}
};
// src/message/segment/Rps.ts
import { defineEnum } from "@ceale/util";
var RpsState = defineEnum("ROCK", "SCISSORS", "PAPER");
var Rps = class _Rps extends MessageSegment {
constructor(state) {
super();
this.state = state;
}
toJSON() {
let result = void 0;
switch (this.state) {
case RpsState.ROCK:
result = 1;
break;
case RpsState.SCISSORS:
result = 2;
break;
case RpsState.PAPER:
result = 3;
break;
}
return {
type: "dice",
data: {
result
}
};
}
static fromJSON(json) {
let state = void 0;
switch (json?.data?.result) {
case 1:
state = RpsState.ROCK;
break;
case 2:
state = RpsState.SCISSORS;
break;
case 3:
state = RpsState.PAPER;
break;
}
const obj = new this(state);
return obj;
}
clone() {
return new _Rps(this.state);
}
equals(other) {
return this.state === other?.state;
}
};
// src/message/segment/Dice.ts
var Dice = class _Dice extends MessageSegment {
constructor(state) {
super();
this.state = state;
}
static fromJSON(json) {
const obj = new this(json?.data?.result ?? void 0);
return obj;
}
toJSON() {
return {
type: "dice",
data: {
result: this.state
}
};
}
clone() {
return new _Dice(this.state);
}
equals(other) {
return this.state === other?.state;
}
};
// src/message/segment/Poke.ts
var Poke = class _Poke extends MessageSegment {
constructor(type, id) {
super();
this.type = type;
this.id = id;
}
toJSON() {
return {
type: "poke",
data: {
type: this.type,
id: this.id
}
};
}
static fromJSON(obj) {
return new this(
obj?.data?.type ?? "",
obj?.data?.id ?? ""
);
}
clone() {
return new _Poke(this.type, this.id);
}
equals(other) {
return this.type === other?.type && this.id === other?.id;
}
};
// src/message/MessageBuilder.ts
var MessageBuilder = class {
segments = [];
build() {
return new Message(this.segments);
}
template(strings, ...values) {
strings.forEach((str, i) => {
if (str !== "") this.segments.push(new Text(str));
if (values[i] !== void 0) {
if (values[i] instanceof MessageSegment) this.segments.push(values[i]);
else this.segments.push(new Text(String(values[i])));
}
});
return this;
}
append(...segments) {
this.segments.push(...segments);
return this;
}
text(...params) {
this.segments.push(new Text(...params));
return this;
}
at(...params) {
this.segments.push(new At(...params));
return this;
}
reply(...params) {
this.segments.push(new Reply(...params));
return this;
}
face(...params) {
this.segments.push(new Face(...params));
return this;
}
rps(...params) {
this.segments.push(new Rps(...params));
return this;
}
dice(...params) {
this.segments.push(new Dice(...params));
return this;
}
image(...params) {
this.segments.push(new Image(...params));
return this;
}
sticker(...params) {
this.segments.push(new Sticker(...params));
return this;
}
mface(...params) {
this.segments.push(new Mface(...params));
return this;
}
poke(...params) {
this.segments.push(new Poke(...params));
return this;
}
};
// src/message/Segment.ts
import "@ceale/util";
var Segment = class {
static fromJSON(json) {
switch (json?.type) {
case "text":
return Text.fromJSON(json);
case "at":
return At.fromJSON(json);
case "reply":
return Reply.fromJSON(json);
case "face":
return Face.fromJSON(json);
case "rps":
return Rps.fromJSON(json);
case "dice":
return Dice.fromJSON(json);
case "image":
if (json?.data?.sub_type === 1) return Sticker.fromJSON(json);
if (Object.hasOwn(json?.data ?? {}, "emoji_id")) return Mface.fromJSON(json);
return Image.fromJSON(json);
case "poke":
return Poke.fromJSON(json);
default:
return void 0;
}
}
static text(...params) {
return new Text(...params);
}
static at(...params) {
return new At(...params);
}
static reply(...params) {
return new Reply(...params);
}
static face(...params) {
return new Face(...params);
}
static rps(...params) {
return new Rps(...params);
}
static dice(...params) {
return new Dice(...params);
}
static image(...params) {
return new Image(...params);
}
static sticker(...params) {
return new Sticker(...params);
}
static mface(...params) {
return new Mface(...params);
}
static poke(...params) {
return new Poke(...params);
}
};
// src/message/Message.ts
var Message = class _Message {
static builder() {
return new MessageBuilder();
}
static template(...params) {
return _Message.builder().template(...params).build();
}
static create(...segments) {
return new _Message(segments.map((segment) => {
return typeof segment === "string" ? new Text(segment) : segment;
}));
}
static fromJSON(json) {
if (typeof json === "string") {
return new _Message([new Text(json)]);
}
if (!Array.isArray(json)) {
throw new TypeError("\u6D88\u606F\u6BB5\u5FC5\u987B\u662F array \u6216 string");
}
const segments = json.map((segment) => Segment.fromJSON(segment)).filter((segment) => segment !== void 0);
return new _Message(segments);
}
segments = [];
getAllSegment() {
return this.segments;
}
getSegment(index) {
return this.segments[index] ?? null;
}
get length() {
return this.segments.length;
}
constructor(segments) {
this.segments = segments;
}
[Symbol.iterator]() {
return this.segments[Symbol.iterator]();
}
toJSON() {
return this.segments.map((segment) => segment.toJSON());
}
clone() {
return new _Message(this.segments.map((segment) => segment.clone()));
}
cloneToBuilder() {
return _Message.builder().append(...this.clone().segments);
}
/**
*
* @param start 可以为负,负就是从尾部开始
* @param deleteCount
* @param segments
*/
splice(start, deleteCount, ...segments) {
const normalizedStart = start < 0 ? Math.max(this.segments.length + start, 0) : Math.min(start, this.segments.length);
const actualDeleteCount = Math.max(
0,
Math.min(deleteCount, this.segments.length - normalizedStart)
);
const deleted = this.segments.splice(normalizedStart, actualDeleteCount, ...segments);
return deleted;
}
text() {
return this.segments.filter((segment) => segment instanceof Text).map((segment) => segment.text).join("");
}
hasSegment(predicate) {
return this.segments.some(predicate);
}
hasSegmentByType(type) {
return this.segments.some((segment) => segment instanceof type);
}
findSegment(predicate) {
return this.segments.find(predicate) ?? null;
}
findSegmentByType(type) {
return this.segments.find((segment) => segment instanceof type) ?? null;
}
findAllSegment(predicate) {
return this.segments.filter(predicate);
}
findAllSegmentByType(type) {
return this.segments.filter((segment) => segment instanceof type);
}
equals(other) {
return this.length === other.length && this.constructor === other.constructor && this.segments.every(
(segment, index) => other.segments[index] && segment?.equals?.(other.segments[index])
);
}
};
// src/NapCatClient.ts
import "node:events";
// src/WebSocketManager.ts
import WebSocket from "ws";
import { defineEnum as defineEnum2, tryCatch as tryCatch3, wait } from "@ceale/util";
// src/util/AutoBind.ts
var BindThis = (target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;
return {
configurable: true,
get() {
const boundFn = originalMethod.bind(this);
Object.defineProperty(this, propertyKey, {
value: boundFn,
configurable: true,
writable: true
});
return boundFn;
}
};
};
// src/WebSocketManager.ts
var WebsocketState = defineEnum2(
"CONNECT",
"ACTIVE",
"CLOSE"
);
var WebsocketManagerState = defineEnum2(
"OPEN",
"CLOSE"
);
var WebSocketManager = class {
constructor(wsParams, dataHandler, retryCfg, logger, timeout) {
this.wsParams = wsParams;
this.dataHandler = dataHandler;
this.retryCfg = retryCfg;
this.logger = logger;
this.timeout = timeout;
}
/** WebSocketManager状态 */
wsmState = WebsocketManagerState.CLOSE;
/** WebSocketManager状态判断 */
wsmStateIs = (value) => this.wsmState === value;
/** 等待关闭的Promise */
waitCloseResolve;
async open() {
this.logger.debug("@WebSocketManager.open()");
if (this.wsmState === WebsocketManagerState.OPEN) return true;
this.wsmState = WebsocketManagerState.OPEN;
const isConnect = await this.connect();
if (this.wsmStateIs(WebsocketManagerState.CLOSE)) {
this.waitCloseResolve?.();
return false;
} else if (isConnect) {
return true;
} else {
return await this.retry();
}
}
async retry() {
this.logger.debug("@WebSocketManager.retry()");
const { interval, limit } = this.retryCfg;
const isInfinity = limit === -1;
for (let count = 0; isInfinity || count < limit; count++) {
this.logger.info(`\u5C06\u5728 ${interval}ms \u540E\u8FDB\u884C\u7B2C ${count + 1} \u6B21\u91CD\u8FDE`);
await wait(this.retryCfg.interval);
if (this.wsmStateIs(WebsocketManagerState.CLOSE)) {
this.waitCloseResolve?.();
return false;
}
this.logger.info(`\u91CD\u65B0\u8FDE\u63A5\u4E2D`);
if (await this.connect()) return true;
}
return false;
}
async close() {
this.logger.debug("@WebSocketManager.close()");
if (this.wsmState === WebsocketManagerState.CLOSE) {
return true;
}
this.wsmState = WebsocketManagerState.CLOSE;
this.ws?.close();
await new Promise((resolve) => {
this.waitCloseResolve = resolve;
});
return true;
}
/** WebSocket状态 */
wsState = WebsocketState.CLOSE;
ws = null;
/** 等待WS连接完成(成功或失败)*/
waitActiveResolve;
waitActiveTimeout;
connect() {
return new Promise((resolve) => {
this.logger.debug("@WebSocketManager.connect()");
this.ws = new WebSocket(...this.wsParams);
this.wsState = WebsocketState.CONNECT;
this.waitActiveResolve = resolve;
this.logger.info("\u6B63\u5728\u5EFA\u7ACBWebSocket\u8FDE\u63A5");
this.ws.addEventListener("open", () => {
if (this.timeout !== -1) {
this.waitActiveTimeout = setTimeout(() => {
this.logger.warn("\u5EFA\u7ACB\u8FDE\u63A5\u65F6\u53D1\u751F\u9519\u8BEF\uFF1A\u7B49\u5F85\u8D85\u65F6");
this.ws?.close();
}, this.timeout);
}
this.ws?.addEventListener("message", this.onceMsg, { once: true });
});
this.ws.addEventListener("close", this.onClose);
});
}
sendData(data) {
if (!this.ws) {
this.logger.warn("\u53D1\u9001\u6570\u636E\u65F6\u53D1\u751F\u9519\u8BEF\uFF1AWebSocket\u6682\u672A\u8FDE\u63A5");
return false;
}
this.ws.send(JSON.stringify(data));
return true;
}
onceMsg(event) {
clearTimeout(this.waitActiveTimeout);
const [data] = tryCatch3(() => JSON.parse(event.data.toString()));
const isMetaConnectPacket = data?.post_type === "meta_event" && data?.meta_event_type === "lifecycle" && data?.sub_type === "connect";
if (isMetaConnectPacket) {
this.dataHandler(data);
this.onActive();
} else {
if (data?.status !== void 0) {
this.logger.warn(`\u5EFA\u7ACB\u8FDE\u63A5\u65F6\u53D1\u751F\u9519\u8BEF\uFF1A`, data);
} else {
this.logger.warn("\u5EFA\u7ACB\u8FDE\u63A5\u65F6\u53D1\u751F\u9519\u8BEF\uFF1A\u9996\u4E2A\u6570\u636E\u5305\u4E0D\u662F OneBot.meta_event.connect");
}
this.ws?.close();
}
}
onActive() {
this.wsState = WebsocketState.ACTIVE;
this.waitActiveResolve?.(true);
this.ws?.addEventListener("message", this.onMsg);
this.logger.info("\u8FDE\u63A5\u6210\u529F");
}
onMsg(event) {
const [data, error] = tryCatch3(() => JSON.parse(event.data.toString()));
if (data) {
this.dataHandler(data);
} else {
this.logger.warn("\u63A5\u6536\u6570\u636E\u65F6\u53D1\u751F\u9519\u8BEF\uFF1A\u89E3\u6790\u6570\u636E\u5931\u8D25");
this.logger.warn(event.data?.toString());
this.logger.warn(error);
}
}
onClose(event) {
clearTimeout(this.waitActiveTimeout);
if (this.wsState === WebsocketState.CONNECT) {
this.waitActiveResolve?.(false);
this.logger.warn("\u5EFA\u7ACB\u8FDE\u63A5\u5931\u8D25\uFF1A", event.code, event.reason);
} else if (this.wsState === WebsocketState.ACTIVE) {
if (this.wsmState === WebsocketManagerState.OPEN) {
this.logger.warn("\u8FDE\u63A5\u5DF2\u65AD\u5F00\uFF1A", event.code, event.reason);
this.retry();
} else if (this.wsmState === WebsocketManagerState.CLOSE) {
this.waitCloseResolve?.();
}
}
this.wsState = WebsocketState.CLOSE;
this.ws = null;
}
};
__decorateClass([
BindThis
], WebSocketManager.prototype, "open", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "retry", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "close", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "connect", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "sendData", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "onceMsg", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "onActive", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "onMsg", 1);
__decorateClass([
BindThis
], WebSocketManager.prototype, "onClose", 1);
// src/NapCatClient.ts
import { assert as assert2, defineEnum as defineEnum3 } from "@ceale/util";
import console2 from "node:console";
// src/service/NCMessage.ts
var NCMessage = class {
NCClient;
Logger;
debug;
constructor({
NCClient,
Logger = console
}, {
debug = false
} = {}) {
this.NCClient = NCClient;
this.Logger = Logger;
this.debug = debug;
}
sendMessage() {
}
onMessage() {
}
};
__decorateClass([
BindThis
], NCMessage.prototype, "sendMessage", 1);
__decorateClass([
BindThis
], NCMessage.prototype, "onMessage", 1);
// src/service/NCSelf.ts
import "@ceale/util";
var NCSelf = class {
NCClient;
Logger;
debug;
waitReady;
isReady = false;
constructor({
NCClient,
Logger = console
}, {
debug = false
} = {}) {
this.NCClient = NCClient;
this.Logger = Logger;
this.debug = debug;
this.waitReady = new Promise(async (resolve) => {
if (this.NCClient.state === NapcatClientState.OPEN) {
const { data } = await this.NCClient.sendAction("get_login_info");
this._user_id = data.user_id;
await this.regetInfo();
this.isReady = true;
resolve();
} else {
NCClient.onceEvent("meta_event.lifecycle.connect", async (data) => {
this._user_id = data.self_id;
await this.regetInfo();
this.isReady = true;
resolve();
});
}
});
}
_raw_info;
get raw_info() {
return this._raw_info;
}
async regetInfo() {
if (!this.user_id) return false;
const data = await this.NCClient.sendAction("get_stranger_info", { user_id: this.user_id });
if (data?.retcode !== 0) return false;
this._raw_info = data?.data;
this._nickname = data?.data.nickname;
}
_user_id;
get user_id() {
return this._user_id;
}
_nickname;
get nickname() {
return this._nickname;
}
async setNickname(name) {
this.NCClient.sendAction("get_login_info");
}
// private _a
getAvatar() {
const size = 0;
const url = `https://thirdqq.qlogo.cn/g?b=sdk&s=${size}&nk=${this.user_id}`;
}
info;
async getInfo() {
return await this.NCClient.sendAction("get_login_info");
}
async setInfo() {
}
};
// src/NapCatClient.ts
var NapcatClientState = defineEnum3("OPEN", "CLOSE");
var NapCatClient2 = class {
// 配置
url;
token;
debug;
timeout;
// 基础服务
logger;
wsManager;
_state = NapcatClientState.CLOSE;
get state() {
return this._state;
}
get wsState() {
return this.wsManager.wsState;
}
// 功能模块
// public Self: NCSelf
Message;
constructor(url, {
token = null,
timeout = 5e3,
retry: {
interval = 5e3,
limit = 5
} = {},
logger = console2,
debug = false
} = {}) {
if (url === void 0) throw new TypeError("url\u53C2\u6570\u662F\u5FC5\u987B\u7684");
this.url = url;
this.token = token;
this.debug = debug;
this.timeout = timeout;
this.logger = {
debug: this.debug ? logger.debug : () => {
},
info: logger.info,
warn: logger.warn,
error: logger.error
};
const headers = { ...this.token ? { Authorization: this.token } : {} };
this.wsManager = new WebSocketManager(
[this.url, { headers }],
this.dataHandler,
{ interval, limit },
this.logger,
this.timeout
);
this.Message = new NCMessage({ NCClient: this, Logger: this.logger }, { debug: this.debug });
}
async connect() {
if (this.state === NapcatClientState.OPEN) return true;
const success = await this.wsManager.open();
if (success) this._state = NapcatClientState.OPEN;
return success;
}
async close() {
if (this.state === NapcatClientState.CLOSE) return true;
const success = await this.wsManager.close();
if (success) this._state = NapcatClientState.CLOSE;
return success;
}
sendData(data) {
this.logger.debug("\u53D1\u9001\u6570\u636E", data);
return this.wsManager.sendData(data);
}
dataHandler(data) {
this.logger.debug("\u63A5\u6536\u6570\u636E", data);
this.dataMap.forEach((handler) => handler(data));
if (data.hasOwnProperty("post_type")) {
this.postDataHandler(data);
} else {
this.actionRespHandler(data);
}
}
dataMap = /* @__PURE__ */ new Set();
onData(handler) {
this.dataMap.add(handler);
}
offData(handler) {
this.dataMap.delete(handler);
}
actionMap = /* @__PURE__ */ new Map();
sendAction(action, params = {}) {
return new Promise((resolve) => {
const id = (Date.now().toString(36) + Math.random().toString(36).slice(2)).slice(0, 16).padEnd(16, "x");
this.actionMap.set(id, resolve);
this.sendData({
action,
params,
echo: id
});
if (this.timeout !== -1) setTimeout(() => {
this.actionMap.delete(id);
resolve({
status: "timeout",
retcode: 1408,
mas: "action timeout",
wording: `Action "${action}" \u54CD\u5E94\u8D85\u65F6 (${this.timeout}ms)`,
data: {},
echo: id
});
}, this.timeout);
});
}
actionRespHandler(data) {
this.actionMap.get(data.echo)?.(data);
this.actionMap.delete(data.echo);
}
eventMap = /* @__PURE__ */ new Map();
postDataHandler(data) {
const eventNamePath = [];
if (data?.post_type) eventNamePath.push(data?.post_type);
const postTypeKey = data.post_type + "_type";
if (data[postTypeKey]) eventNamePath.push(data[postTypeKey]);
if (data?.sub_type) eventNamePath.push(data?.sub_type);
this.logger.debug("\u63A5\u6536\u5230\u4E8B\u4EF6\uFF1A", eventNamePath);
for (let i = eventNamePath.length; i > 0; i--) {
const eventName = eventNamePath.slice(0, i).join(".");
this.eventMap.get(eventName)?.forEach((handler) => handler(data));
}
this.eventMap.get("all")?.forEach((handler) => handler(data));
}
onEvent(arg1, arg2) {
const [eventName, handler] = arg2 ? [arg1, arg2] : ["all", arg2];
assert2(eventName);
assert2(handler);
let eventSet = this.eventMap.get(eventName);
if (!eventSet) {
eventSet = /* @__PURE__ */ new Set();
this.eventMap.set(eventName, eventSet);
}
eventSet.add(handler);
}
onceEvent(arg1, arg2) {
const [eventName, handler] = arg2 ? [arg1, arg2] : ["all", arg2];
assert2(eventName);
assert2(handler);
const onceHandler = (data) => {
this.offEvent(eventName, onceHandler);
handler(data);
};
this.onEvent(eventName, onceHandler);
}
offEvent(arg1, arg2) {
const [eventName, handler] = arg2 ? [arg1, arg2] : ["all", arg2];
assert2(eventName);
assert2(handler);
let eventSet = this.eventMap.get(eventName);
if (eventSet) {
eventSet.delete(handler);
}
}
};
__decorateClass([
BindThis
], NapCatClient2.prototype, "connect", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "close", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "sendData", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "dataHandler", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "sendAction", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "actionRespHandler", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "postDataHandler", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "onEvent", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "onceEvent", 1);
__decorateClass([
BindThis
], NapCatClient2.prototype, "offEvent", 1);
export {
At,
BindThis,
Dice,
Face,
Image,
Message,
MessageBuilder,
MessageSegment,
Mface,
NCMessage,
NCSelf,
NapCatClient2 as NapCatClient,
NapcatClientState,
Poke,
Reply,
Rps,
RpsState,
Segment,
Sticker,
Text,
WebSocketManager
};