2020-06-30 10:13:58 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2020-05-02 20:03:36 +08:00
|
|
|
import re
|
2020-05-05 16:11:05 +08:00
|
|
|
from typing import Union, Callable, Optional
|
|
|
|
|
2020-07-05 20:39:34 +08:00
|
|
|
from nonebot.event import Event
|
2020-05-02 20:03:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Rule:
|
|
|
|
|
2020-05-05 16:11:05 +08:00
|
|
|
def __init__(self, checker: Optional[Callable[[Event], bool]] = None):
|
|
|
|
self.checker = checker or (lambda event: True)
|
2020-05-02 20:03:36 +08:00
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
def __call__(self, event: Event) -> bool:
|
2020-05-02 20:03:36 +08:00
|
|
|
return self.checker(event)
|
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
def __and__(self, other: "Rule") -> "Rule":
|
2020-05-02 20:03:36 +08:00
|
|
|
return Rule(lambda event: self.checker(event) and other.checker(event))
|
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
def __or__(self, other: "Rule") -> "Rule":
|
2020-05-02 20:03:36 +08:00
|
|
|
return Rule(lambda event: self.checker(event) or other.checker(event))
|
|
|
|
|
2020-07-04 22:51:10 +08:00
|
|
|
def __neg__(self) -> "Rule":
|
2020-05-02 20:03:36 +08:00
|
|
|
return Rule(lambda event: not self.checker(event))
|
|
|
|
|
|
|
|
|
|
|
|
def user(*qq: int) -> Rule:
|
|
|
|
return Rule(lambda event: event.user_id in qq)
|
|
|
|
|
|
|
|
|
|
|
|
def private() -> Rule:
|
|
|
|
return Rule(lambda event: event.detail_type == "private")
|
|
|
|
|
|
|
|
|
|
|
|
def group(*group: int) -> Rule:
|
|
|
|
return Rule(
|
|
|
|
lambda event: event.detail_type == "group" and event.group_id in group)
|
|
|
|
|
|
|
|
|
|
|
|
def discuss(*discuss: int) -> Rule:
|
|
|
|
return Rule(lambda event: event.detail_type == "discuss" and event.
|
|
|
|
discuss_id in discuss)
|
|
|
|
|
|
|
|
|
|
|
|
def startswith(msg, start: int = None, end: int = None) -> Rule:
|
|
|
|
return Rule(lambda event: event.message.startswith(msg, start, end))
|
|
|
|
|
|
|
|
|
|
|
|
def endswith(msg, start: int = None, end: int = None) -> Rule:
|
|
|
|
return Rule(lambda event: event.message.endswith(msg, start=None, end=None))
|
|
|
|
|
|
|
|
|
|
|
|
def has(msg: str) -> Rule:
|
|
|
|
return Rule(lambda event: msg in event.message)
|
|
|
|
|
|
|
|
|
|
|
|
def regex(regex, flags: Union[int, re.RegexFlag] = 0) -> Rule:
|
|
|
|
pattern = re.compile(regex, flags)
|
|
|
|
return Rule(lambda event: bool(pattern.search(event.message)))
|