Skip to content

Commit

Permalink
新增 plugin.awaitContext() 方法
Browse files Browse the repository at this point in the history
  • Loading branch information
TimeRainStarSky committed May 29, 2024
1 parent 3724149 commit ff5a711
Showing 1 changed file with 23 additions and 14 deletions.
37 changes: 23 additions & 14 deletions lib/plugins/plugin.js
Original file line number Diff line number Diff line change
@@ -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 {
/**
Expand Down Expand Up @@ -73,47 +75,54 @@ 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) {
if (type) return stateArr[this.conKey(isGroup)]?.[type]
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 })
}
Expand Down

0 comments on commit ff5a711

Please sign in to comment.