From ff5a711390f62f8ed87fa6095ff8d33c3b04f614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9F=8C=8C?= Date: Thu, 30 May 2024 01:17:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=20plugin.awaitContext()=20?= =?UTF-8?q?=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/plugins/plugin.js | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/lib/plugins/plugin.js b/lib/plugins/plugin.js index 38c0375..154c7cb 100644 --- a/lib/plugins/plugin.js +++ b/lib/plugins/plugin.js @@ -1,6 +1,8 @@ -import { Common } from '#miao' +import { Common } from "#miao" const stateArr = {} +const SymbolTimeout = Symbol("Timeout") +const SymbolResolve = Symbol("Resolve") export default class plugin { /** @@ -73,28 +75,30 @@ export default class plugin { conKey(isGroup = false) { if (isGroup) { - return `${this.name}.${this.e.group_id}` + return `${this.name}.${this.group_id || this.groupId || this.e.group_id}` } else { - return `${this.name}.${this.userId || this.e.user_id}` + return `${this.name}.${this.user_id || this.userId || this.e.user_id}` } } /** * @param type 执行方法 * @param isGroup 是否群聊 - * @param time 操作时间,默认120秒 - * @param reply 超时时回复的内容,false则不回复 + * @param time 操作时间 + * @param timeout 操作超时回复 */ - setContext(type, isGroup, time = 120, reply = "操作超时已取消") { + setContext(type, isGroup, time = 120, timeout = "操作超时已取消") { const key = this.conKey(isGroup) if (!stateArr[key]) stateArr[key] = {} stateArr[key][type] = this.e - if (time) stateArr[key][type].timeout = setTimeout(() => { + if (time) stateArr[key][type][SymbolTimeout] = setTimeout(() => { if (stateArr[key][type]) { + const resolve = stateArr[key][type][SymbolResolve] delete stateArr[key][type] - this.reply(reply, true) + resolve ? resolve(false) : this.reply(timeout, true) } }, time * 1000) + return stateArr[key][type] } getContext(type, isGroup) { @@ -102,18 +106,23 @@ export default class plugin { return stateArr[this.conKey(isGroup)] } - /** - * @param type 执行方法 - * @param isGroup 是否群聊 - */ finish(type, isGroup) { const key = this.conKey(isGroup) - if (stateArr[key] && stateArr[key][type]) { - clearTimeout(stateArr[key][type].timeout) + if (stateArr[key]?.[type]) { + clearTimeout(stateArr[key][type][SymbolTimeout]) delete stateArr[key][type] } } + awaitContext(...args) { + return new Promise(resolve => this.setContext("resolveContext", ...args)[SymbolResolve] = resolve) + } + + resolveContext(context) { + this.finish("resolveContext") + context[SymbolResolve](this.e) + } + async renderImg(plugin, tpl, data, cfg) { return Common.render(plugin, tpl, data, { ...cfg, e: this.e }) }