From f350d971fd5abbee5bdcb9ec6fd30bbb1e9a167b Mon Sep 17 00:00:00 2001 From: wdvxdr Date: Thu, 8 Apr 2021 23:28:06 +0800 Subject: [PATCH] docs(event filter): advance syntax --- docs/EventFilter.md | 31 ++++++++++++++++++++++++++++++- global/config/config.go | 25 ++++++++++++++++--------- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/docs/EventFilter.md b/docs/EventFilter.md index 7f23406..9226b7a 100644 --- a/docs/EventFilter.md +++ b/docs/EventFilter.md @@ -1,6 +1,6 @@ # 事件过滤器 -在go-cqhttp同级目录下新建`filter.json`文件即可开启事件过滤器,启动时会读取该文件中定义的过滤规则(使用 JSON 编写),若文件不存在,或过滤规则语法错误,则不会启用事件过滤器。 +在配置文件填写对应通信方式的 `middlewares.filter` 即可开启事件过滤器,启动时会读取该文件中定义的过滤规则(使用 JSON 编写),若文件不存在,或过滤规则语法错误,则不会启用事件过滤器。 事件过滤器会处理所有事件(包括心跳事件在内的元事件),请谨慎使用!! 注意: 与客户端建立连接的握手事件**不会**经过事件过滤器 @@ -114,6 +114,35 @@ } ``` +## 进阶指南 + +1. 对于嵌套的值,可以使用 `.` 进行简化,如 + +```json +{ + "sender": { + "sex": "male" + } +} +``` + +与下面的配置文件作用相同 + +```json +{ + "sender.sex": "male" +} +``` + +2. 对于数组,可以使用数字索引,如 +```json +{ + "message.0.type": "text" +} +``` + +更多进阶语法请参考[GJSON语法](https://github.com/tidwall/gjson/blob/master/SYNTAX.md) + ## 语法说明 过滤规则最外层是一个 JSON 对象,其中的键,如果以 `.`(点号)开头,则表示运算符,其值为运算符的参数,如果不以 `.` 开头,则表示对事件数据对象中相应键的过滤。过滤规则中任何一个对象,只有在它的所有项都匹配的情况下,才会让事件通过(等价于一个 `and` 运算);其中,不以 `.` 开头的键,若其值不是对象,则只有在这个值和事件数据相应值相等的情况下,才会通过(等价于一个 `eq` 运算符)。 diff --git a/global/config/config.go b/global/config/config.go index fc6d25e..26849e5 100644 --- a/global/config/config.go +++ b/global/config/config.go @@ -5,6 +5,7 @@ import ( _ "embed" // embed the default config file "os" "path" + "sync" log "github.com/sirupsen/logrus" "gopkg.in/yaml.v3" @@ -110,17 +111,23 @@ type LevelDBConfig struct { Enable bool `yaml:"enable"` } +var ( + config *Config + once sync.Once +) + // Get 从默认配置文件路径中获取 func Get() *Config { - file, err := os.Open(DefaultConfigFile) - if err != nil { - log.Error("获取配置文件失败: ", err) - return nil - } - config := &Config{} - if yaml.NewDecoder(file).Decode(config) != nil { - log.Fatal("配置文件不合法!", err) - } + once.Do(func() { + file, err := os.Open(DefaultConfigFile) + if err != nil { + log.Error("获取配置文件失败: ", err) + } + config = &Config{} + if yaml.NewDecoder(file).Decode(config) != nil { + log.Fatal("配置文件不合法!", err) + } + }) return config }