Skip to content

Commit

Permalink
fix: 更强壮的事件过滤器
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-cn committed Oct 13, 2023
1 parent 7cde499 commit b92372a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ general: # 通用配置,在单个配置省略时的默认值
## 语法说明
- `onebots` 的事件过滤器嘴歪成是一个JSON对象,其中的键是键如果是运算法,则值作为运算符的参数,如果不是运算符,则表示对事件数据对象相应 `key` 进行过滤。
- 过滤规则中任何一个对象, 只有在它的所有项都匹配的情况下, 才会让事件通过(等价于一个 and 运算),如果值为一个数组,则表示事件对应 `key` 值需满足其中一个。
- 可用运算符有`$and``$or``$not`
- 可用逻辑运算符有`$and` (逻辑与) `$or` (逻辑或) `$not` (逻辑非)、`$nor` (逻辑异或)、`$regexp` (文本正则匹配)、`$like` (文本模糊匹配)、`$gt` (数值大于比较)、`$gte` (数值大于等于比较)、`$lt` (数值小于比较)、`$lte` (数值小于等于比较)、`$between` (数值范围比较)
## 示例
### 1. 仅上报私聊事件
```yaml
Expand Down Expand Up @@ -178,6 +178,13 @@ filters:
message_type: group
group_id: 987654321
```
### 5. 用户年龄大于18岁
```yaml
filters:
sender:
age:
$gt: 18
```
# 使用API管理oneBot
| url | method | params | desc |
Expand Down
18 changes: 17 additions & 1 deletion src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ export namespace Service{
key: string,
value: any,
) => {
if(key === "$and" || key === "$or" || key === "$not") {
// 如果 key 为 $and、$or、$not、$nor 则递归调用
if(key === "$and" || key === "$or" || key === "$not" || key==='$nor') {
if(!value || typeof value!=='object') throw new Error("invalid filter");
switch (key) {
case "$and":
Expand All @@ -43,6 +44,8 @@ export namespace Service{
case "$or":
return Array.isArray(value)? value.some((item) => filterFn(event, key, item)) :
Object.entries(value).some(([key, value]) => filterFn(event, key, value));
case "$nor":
return !filterFn(event,'$or', value);
case "$not":
return !filterFn(event, '$and', value);
}
Expand All @@ -51,8 +54,21 @@ export namespace Service{
return value;
}
if (typeof value !== "object") {
if(key==='$regex' && typeof value==='string') return new RegExp(value).test(event[key]);
if(key==='$like' && typeof value==='string') return event[key].includes(value);
if(key==='$gt' && typeof value==='number') return event[key]>value;
if(key==='$gte' && typeof value==='number') return event[key]>=value;
if(key==='$lt' && typeof value==='number') return event[key]<value;
if(key==='$lte' && typeof value==='number') return event[key]<=value;
return value === event[key];
}
if(key==='$between' &&
Array.isArray(value) &&
value.length === 2 &&
value.every((item) => typeof item === 'number')){
const [start,end]=value;
return event[key]>=start && event[key]<=end;
}
if(Array.isArray(value)){
return value.includes(event[key]);
}
Expand Down

0 comments on commit b92372a

Please sign in to comment.