github.com/fumiama/NanoBot@v0.0.0-20231122134259-c22d8183efca/engine.go (about)

     1  package nano
     2  
     3  //go:generate go run codegen/engine/main.go
     4  
     5  // 生成空引擎
     6  func newEngine() *Engine {
     7  	return &Engine{
     8  		preHandler:  []Rule{},
     9  		midHandler:  []Rule{},
    10  		postHandler: []Process{},
    11  	}
    12  }
    13  
    14  var defaultEngine = newEngine()
    15  
    16  // Engine is the pre_handler, mid_handler, post_handler manager
    17  type Engine struct {
    18  	preHandler  []Rule
    19  	midHandler  []Rule
    20  	postHandler []Process
    21  	matchers    []*Matcher
    22  	prio        int
    23  	service     string
    24  	datafolder  string
    25  }
    26  
    27  // Delete 移除该 Engine 注册的所有 Matchers
    28  func (e *Engine) Delete() {
    29  	for _, m := range e.matchers {
    30  		m.Delete()
    31  	}
    32  }
    33  
    34  // UsePreHandler 向该 Engine 添加新 PreHandler(Rule),
    35  // 会在 Rule 判断前触发,如果 preHandler
    36  // 没有通过,则 Rule, Matcher 不会触发
    37  //
    38  // 可用于分群组管理插件等
    39  func (e *Engine) UsePreHandler(rules ...Rule) {
    40  	e.preHandler = append(e.preHandler, rules...)
    41  }
    42  
    43  // UseMidHandler 向该 Engine 添加新 MidHandler(Rule),
    44  // 会在 Rule 判断后, Matcher 触发前触发,如果 midHandler
    45  // 没有通过,则 Matcher 不会触发
    46  //
    47  // 可用于速率限制等
    48  func (e *Engine) UseMidHandler(rules ...Rule) {
    49  	e.midHandler = append(e.midHandler, rules...)
    50  }
    51  
    52  // UsePostHandler 向该 Engine 添加新 PostHandler(Rule),
    53  // 会在 Matcher 触发后触发,如果 PostHandler 返回 false,
    54  // 则后续的 post handler 不会触发
    55  //
    56  // 可用于速率限制等
    57  func (e *Engine) UsePostHandler(handler ...Process) {
    58  	e.postHandler = append(e.postHandler, handler...)
    59  }
    60  
    61  // ApplySingle 应用反并发
    62  func (e *Engine) ApplySingle(s *Single[int64]) *Engine {
    63  	s.Apply(e)
    64  	return e
    65  }
    66  
    67  // DataFolder 本插件数据目录, 默认 data/rbp/
    68  func (e *Engine) DataFolder() string {
    69  	return e.datafolder
    70  }
    71  
    72  // On 添加新的指定消息类型的匹配器(默认Engine)
    73  func On(typ string, rules ...Rule) *Matcher { return defaultEngine.On(typ, rules...) }
    74  
    75  // On 添加新的指定消息类型的匹配器
    76  func (e *Engine) On(typ string, rules ...Rule) *Matcher {
    77  	matcher := &Matcher{
    78  		Type:   typ,
    79  		Rules:  rules,
    80  		Engine: e,
    81  	}
    82  	e.matchers = append(e.matchers, matcher)
    83  	return StoreMatcher(matcher)
    84  }