aboutsummaryrefslogtreecommitdiffstatshomepage
diff options
context:
space:
mode:
-rw-r--r--README.md93
-rw-r--r--src/hydrorollcore/__init__.py4
-rw-r--r--src/hydrorollcore/cli.py38
-rw-r--r--src/hydrorollcore/consts/__init__.py0
-rw-r--r--src/hydrorollcore/consts/templates.py63
-rw-r--r--src/hydrorollcore/event.py12
-rw-r--r--src/hydrorollcore/log.py35
-rw-r--r--src/hydrorollcore/rule.py51
-rw-r--r--src/hydrorollcore/settings.py1
-rw-r--r--src/hydrorollcore/utils.py2
10 files changed, 229 insertions, 70 deletions
diff --git a/README.md b/README.md
index aa8cb626..0dc52238 100644
--- a/README.md
+++ b/README.md
@@ -1,63 +1,78 @@
<h1 align="right">HydroRollCore'水系核心</h1>
<p align="right">
- <a aria-label="Join the community on GitHub" href="https://github.com/HydroRoll-Team/hydroroll/discussions" target="blank">
- <img alt="" src="https://img.shields.io/badge/Join%20the%20community-blueviolet.svg?logo=data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8CAgL/CgoK/woKCv8GBgb/BgYG/woKCv8KCgr/AgIC/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/BgYG/0ZGRv9MTEz/JiYm/ygoKP9MTEz/RkZG/wYGBv8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP9ycnL/Li4u/1xcXP9eXl7/Li4u/3Jycv8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP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">
- </a>
- <a href="https://pypi.org/project/HydroRollCore">
- <img src="https://img.shields.io/pypi/v/hydrorollcore?labelColor=000000">
- </a>
- <a href="https://github.com/HydroRoll-Team/HydroRollCore/blob/master/LICENSE">
- <img alt="" src="https://img.shields.io/pypi/l/hydrorollcore.svg?labelColor=000000&color=">
- </a>
-
- [![.github/workflows/python-publish.yml](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/python-publish.yml/badge.svg)](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/python-publish.yml)
- [![CodeQL](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/codeql.yml/badge.svg)](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/codeql.yml)
- [![Netlify Status](https://api.netlify.com/api/v1/badges/ecbe4af3-223f-4fa4-a182-a37a776fd05b/deploy-status)](https://app.netlify.com/sites/grps-v1/deploys)
+ <a aria-label="Join the community on GitHub" href="https://github.com/HydroRoll-Team/hydroroll/discussions" target="blank">
+ <img alt="" src="https://img.shields.io/badge/Join%20the%20community-blueviolet.svg?logo=data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8CAgL/CgoK/woKCv8GBgb/BgYG/woKCv8KCgr/AgIC/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/BgYG/0ZGRv9MTEz/JiYm/ygoKP9MTEz/RkZG/wYGBv8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP9ycnL/Li4u/1xcXP9e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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==&labelColor=000000&logoWidth=20&logoColor=white">
+ </a>
+ <a href="https://pypi.org/project/HydroRollCore">
+ <img alt="pypi" src="https://img.shields.io/pypi/v/hydrorollcore?labelColor=000000">
+ </a>
+ <a href="https://github.com/HydroRoll-Team/HydroRollCore/blob/master/LICENSE">
+ <img alt="hydro" src="https://img.shields.io/pypi/l/hydrorollcore.svg?labelColor=000000&color=">
+ </a>
+
+[![.github/workflows/python-publish.yml](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/python-publish.yml/badge.svg)](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/python-publish.yml)
+[![CodeQL](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/codeql.yml/badge.svg)](https://github.com/HydroRoll-Team/HydroRollCore/actions/workflows/codeql.yml)
+[![Netlify Status](https://api.netlify.com/api/v1/badges/ecbe4af3-223f-4fa4-a182-a37a776fd05b/deploy-status)](https://app.netlify.com/sites/grps-v1/deploys)
</p>
-## 🎁 Getting <img align="right" src="https://mirror.ghproxy.com/https://raw.githubusercontent.com/HydroRoll-Team/HydroRoll/main/site/src/assets/image/logo.png" height="120">
+## 🎁 Getting <img align="right" alt="hydro" src="https://mirror.ghproxy.com/https://raw.githubusercontent.com/HydroRoll-Team/HydroRoll/main/site/src/assets/image/logo.png" height="120">
+
+> [!IMPORTANT]
+>
+> 强烈推荐使用`pdm`管理你的`HydroBot`项目。
1. 安装库
-> [!IMPORTANT]
->
-> 强烈推荐使用`pdm`管理你的`Bot`项目。
+ 在终端中执行:
+
+ ```bash
+ git clone https://github.com/HydroRoll-Team/HydroRollCore.git
+ cd HydroRollCore
+ pdm install
+ ```
-在命令行输入。
+ 你可以使用`pip`进行安装:
-``` shell
-git clone https://github.com/HydroRoll-Team/HydroRollCore.git
-cd HydroRollCore
-pdm install
-# 或者使用pip
-# pip install HydroRollCore
-```
+ ```bash
+ pip install HydroRollCore
+ ```
2. 创建规则包实例
-``` shell
-mkdir myrules && cd myrules && mkdir rule1
-echo.> config.toml
-echo.> __init__.py
-```
+ ``` shell
+ mkdir myrules && cd myrules && mkdir rule1
+ echo.> config.toml
+ echo.> __init__.py
+ ```
-在 `__init__.py` 创建一个 `rule` 实例并继承 `Rule` 基类, 通过编写合适的相关方法与类注册规则包实现规则的自定义。
+ 在 `__init__.py` 创建一个 `rule` 实例并继承 `Rule` 基类, 通过编写合适的相关方法与类注册规则包实现规则的自定义。
-``` python
-from HydroRollCore import Rule
+ ``` python
+ from HydroRollCore import Rule, Result, Dice
-class Myrule(Rule):
- """自设规则包,继承 Rules 基类"""
-```
+ class MyRule(Rule):
+ """自设规则包"""
+
+ name = "MyRule"
+ priority: int = 0
+
+ def __init__(self) -> None:
+ """初始化你的规则包"""
+
+ def check(self, dice: Dice) -> Result:
+ """声明规则包检定方式"""
+ return Result("myevent.event1", True)
+ ```
3. 合理修改你的 `config.toml` 配置文件,完成注册!
### 🎍Sites
-https://grps.hydroroll.team _(recommend)_
-https://grps-v1.netlify.app
-~~https://hydroroll-team.github.io/HydroRollCore/~~
+
+<https://grps.hydroroll.team> _(recommend)_
+<https://grps-v1.netlify.app>
+~~<https://hydroroll-team.github.io/HydroRollCore/>~~
## 📄 License
diff --git a/src/hydrorollcore/__init__.py b/src/hydrorollcore/__init__.py
index f0a096fd..7a2bba77 100644
--- a/src/hydrorollcore/__init__.py
+++ b/src/hydrorollcore/__init__.py
@@ -1,6 +1,6 @@
from HydroRollCore.cli import Cli
from HydroRollCore.config import Config
-from HydroRollCore.rule import Rule
+from HydroRollCore.rule import Rule, Result, Dice
from HydroRollCore.core import Core
-__all__ = ["Core", "Rule", "Config", "Cli"]
+__all__ = ["Core", "Rule", "Config", "Cli", "Result", "Dice"]
diff --git a/src/hydrorollcore/cli.py b/src/hydrorollcore/cli.py
index 8ce0fd9e..5351d96d 100644
--- a/src/hydrorollcore/cli.py
+++ b/src/hydrorollcore/cli.py
@@ -1,22 +1,40 @@
+from pathlib import Path
+from .consts import templates
+
+# from tkinter import messagebox
+
import argparse
-from tkinter import messagebox
+import os
+import sys
class Cli:
def parse_args(self):
- # 创建解析器对象
parser = argparse.ArgumentParser(description="HydroRoll 命令行工具")
- # 添加命令行参数
- parser.add_argument("--gui", action="store_true", help="显示弹窗")
+ parser.add_argument("--new", action="store_true", help="创建一个 HydroRoll 规则包模板")
+ parser.add_argument("--run", action="store_true", help="运行 HydroRoll 规则包")
+ # parser.add_argument("--gui", action="store_true", help="显示弹窗")
parser.add_argument("--path", help="指定路径")
- # 解析命令行参数
args = parser.parse_args()
- # 处理命令行参数
- if args.gui:
- messagebox.showinfo("提示", "这是一个弹窗!")
+ # if args.gui:
+ # messagebox.showinfo("提示", "这是一个弹窗!")
+
+ path = Path(args.path).resolve() if args.path else Path(os.getcwd()).resolve()
+ if args.new and args.run:
+ print("无法确定的指令要求: 你同时指定了new与run指令。")
+ sys.exit(1)
+
+ if args.new:
+ if path.exists():
+ print("指定的文件夹已经存在!")
+ sys.exit(1)
+
+ path.mkdir(parents=True, exist_ok=True)
+ (path / "rule.py").write_text(templates.RULE)
+ (path / "event.py").write_text(templates.EVENT)
+ (path / "dice.py").write_text(templates.DICE)
- if args.path:
- print("输入的路径:", args.path)
+ print("HydroRoll 规则包模板已创建!")
diff --git a/src/hydrorollcore/consts/__init__.py b/src/hydrorollcore/consts/__init__.py
new file mode 100644
index 00000000..e69de29b
--- /dev/null
+++ b/src/hydrorollcore/consts/__init__.py
diff --git a/src/hydrorollcore/consts/templates.py b/src/hydrorollcore/consts/templates.py
new file mode 100644
index 00000000..4cf72989
--- /dev/null
+++ b/src/hydrorollcore/consts/templates.py
@@ -0,0 +1,63 @@
+RULE = """from HydroRollCore import Rule, Result, Dice
+
+class MyRule(Rule):
+ \"\"\"自设规则包\"\"\"
+
+ name = "MyRule"
+ priority: int = 0
+
+ def __init__(self) -> None:
+ \"\"\"初始化你的规则包\"\"\"
+
+ def check(self, dice: Dice) -> Result:
+ \"\"\"声明规则包检定方式\"\"\"
+ return Result("myevent.event1", True)
+"""
+
+EVENT = """from HydroRollCore import Event
+
+__events__ = ["MyEvent"]
+
+class MyEvent(Event):
+ name = "event1"
+ output = "检定成功!"
+"""
+
+DICE = """from HydroRollCore import Dice
+
+class BaseDice(Dice):
+ \"\"\"多面骰\"\"\"
+
+ def __init__(self, roll_string: str = "") -> None:
+ self.roll_string = roll_string
+ self.parse()
+
+ def parse(self) -> "Dice":
+ self.dices = []
+ split = re.split(r"[dD]", self.roll_string)
+
+ if split[0]:
+ self.a = int(split[0])
+ else:
+ self.a = 1
+
+ if split[1]:
+ self.b = int(split[1])
+ else:
+ self.b = 100
+
+ self.db = f"{self.a}D{self.b}"
+ self.dices += [f"D{self.b}"] * self.a
+ return self
+
+ def roll(self) -> int:
+ self.results = []
+
+ for _ in range(self.a):
+ result = random.randint(1, self.b)
+
+ self.results.append(result)
+
+ self.outcome = sum(self.results)
+ return self.outcome
+"""
diff --git a/src/hydrorollcore/event.py b/src/hydrorollcore/event.py
new file mode 100644
index 00000000..e8edeb98
--- /dev/null
+++ b/src/hydrorollcore/event.py
@@ -0,0 +1,12 @@
+from abc import ABCMeta
+
+
+class Event(metaclass=ABCMeta):
+ """事件基类"""
+
+ name: str
+ output: str
+
+ def __init__(self, name: str, output: str) -> None:
+ self.name = name
+ self.output = output
diff --git a/src/hydrorollcore/log.py b/src/hydrorollcore/log.py
index 3eb07e7a..ed62d0ae 100644
--- a/src/hydrorollcore/log.py
+++ b/src/hydrorollcore/log.py
@@ -3,29 +3,34 @@
HydroRollCore 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息。
自定义 logger 请参考 [loguru](https://github.com/Delgan/loguru) 文档。
"""
-import os
-import sys
from datetime import datetime
+from multilogging import multilogger
+from pathlib import Path
+from .settings import DEBUG
-from loguru import logger as _logger
__all__ = ["logger", "error_or_exception"]
-logger = _logger
-current_path = os.path.dirname(os.path.abspath("__file__"))
-log_path = os.path.join(
- current_path, "logs", datetime.now().strftime("%Y-%m-%d") + ".log"
+logger = multilogger(
+ name="HydroRoll", payload="Core", level="DEBUG" if DEBUG else "INFO"
)
+current_path = Path(__file__).resolve().parent
+LOG_PATH = current_path / "logs" / (datetime.now().strftime("%Y-%m-%d") + ".log")
+if not LOG_PATH.exists():
+ LOG_PATH.mkdir(parents=True, exist_ok=True)
+logger.add(sink=LOG_PATH, level="INFO", rotation="10 MB") # 每个日志文件最大为 10MB
-def error_or_exception(message: str, exception: Exception, verbose: bool):
- logger.remove()
- logger.add(
- sys.stderr,
- format="<magenta>{time:YYYY-MM-DD HH:mm:ss.SSS}</magenta> <level>[{level}]</level> > <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
- )
- logger.add(sink=log_path, level="INFO", rotation="10 MB") # 每个日志文件最大为 10MB
+def error_or_exception(message: str, exception: Exception, verbose: bool = True):
+ # 弃用的方法
+ # logger.remove()
+ # logger.add(
+ # sys.stderr,
+ # format="<magenta>{time:YYYY-MM-DD HH:mm:ss.SSS}</magenta> <level>[{level}]</level> > <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
+ # )
+
if verbose:
- logger.exception(message)
+ logger.exception(exception)
+ logger.critical(message)
else:
logger.critical(f"{message} {exception!r}")
diff --git a/src/hydrorollcore/rule.py b/src/hydrorollcore/rule.py
index a1b07cb9..127ed805 100644
--- a/src/hydrorollcore/rule.py
+++ b/src/hydrorollcore/rule.py
@@ -1,7 +1,8 @@
from abc import ABCMeta, abstractmethod
from enum import Enum
+from .exceptions import HydroError
-__all__ = ["RuleLoadType", "Rule"]
+__all__ = ["RuleLoadType", "Result", "Dice", "Rule"]
class RuleLoadType(Enum):
@@ -13,6 +14,50 @@ class RuleLoadType(Enum):
CLASS = "class"
+class Result(metaclass=ABCMeta):
+ """规则检定结果基类"""
+
+ event: str
+ status: bool
+ exception: HydroError | None = None
+
+ def __init__(self, event: str, status: bool, exception: HydroError | None) -> None:
+ self.event = event
+ self.status = status
+ self.exception = exception
+
+ def ok(self):
+ """规则执行期间是否产生异常"""
+ return isinstance(self.exception, HydroError)
+
+
+class Dice(metaclass=ABCMeta):
+ """掷骰基类"""
+
+ roll_string: str
+ db: str
+ outcome: int
+
+ def __repr__(self) -> str:
+ return f'<HydroDice "{self.db.upper()}">'
+
+ def __str__(self) -> str:
+ return self.db.upper()
+
+ def __int__(self) -> int:
+ return self.outcome
+
+ @abstractmethod
+ def parse(self) -> "Dice":
+ """解析传入的掷骰字符串`roll_string`,返回一个`Dice`对象"""
+ raise NotImplementedError
+
+ @abstractmethod
+ def roll(self) -> int:
+ """掷骰方法,返回掷骰结果"""
+ raise NotImplementedError
+
+
class Rule(metaclass=ABCMeta):
"""规则基类"""
@@ -20,9 +65,9 @@ class Rule(metaclass=ABCMeta):
priority: int = 0
@abstractmethod
- def __init__(self):
+ def __init__(self) -> None:
raise NotImplementedError
@abstractmethod
- async def run(self):
+ def check(self, dice: Dice) -> Result:
raise NotImplementedError
diff --git a/src/hydrorollcore/settings.py b/src/hydrorollcore/settings.py
new file mode 100644
index 00000000..51c64dd2
--- /dev/null
+++ b/src/hydrorollcore/settings.py
@@ -0,0 +1 @@
+DEBUG = True
diff --git a/src/hydrorollcore/utils.py b/src/hydrorollcore/utils.py
index 71187856..1333815a 100644
--- a/src/hydrorollcore/utils.py
+++ b/src/hydrorollcore/utils.py
@@ -189,4 +189,4 @@ def sync_func_wrapper(
async def _wrapper(*args: _P.args, **kwargs: _P.kwargs):
return func(*args, **kwargs)
- return _wrapper \ No newline at end of file
+ return _wrapper