2024-05-31 19:17:25 +08:00
|
|
|
|
"""
|
|
|
|
|
liteyuki function是一种类似于mcfunction的函数,用于在liteyuki中实现一些功能,例如自定义指令等,也可与Python函数绑定
|
|
|
|
|
使用 /function function_name *args **kwargs来调用
|
|
|
|
|
例如 /function test/hello user_id=123456
|
|
|
|
|
可以用于一些轻量级插件的编写,无需Python代码
|
|
|
|
|
SnowyKami
|
|
|
|
|
"""
|
2024-05-31 22:42:04 +08:00
|
|
|
|
import asyncio
|
2024-05-31 19:17:25 +08:00
|
|
|
|
import functools
|
|
|
|
|
# cmd *args **kwargs
|
|
|
|
|
# api api_name **kwargs
|
|
|
|
|
import os
|
|
|
|
|
from typing import Any, Awaitable, Callable, Coroutine
|
|
|
|
|
|
2024-05-31 22:42:04 +08:00
|
|
|
|
import nonebot
|
2024-05-31 19:17:25 +08:00
|
|
|
|
from nonebot import Bot
|
|
|
|
|
from nonebot.adapters.satori import bot
|
2024-05-31 22:42:04 +08:00
|
|
|
|
from nonebot.internal.matcher import Matcher
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
ly_function_extensions = (
|
|
|
|
|
"lyf",
|
|
|
|
|
"lyfunction",
|
|
|
|
|
"mcfunction"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
loaded_functions = dict()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class LiteyukiFunction:
|
2024-05-31 22:42:04 +08:00
|
|
|
|
def __init__(self, name: str):
|
2024-05-31 19:17:25 +08:00
|
|
|
|
self.name = name
|
2024-05-31 22:42:04 +08:00
|
|
|
|
self.functions: list[str] = list()
|
2024-05-31 19:17:25 +08:00
|
|
|
|
self.bot: Bot = None
|
2024-05-31 22:59:02 +08:00
|
|
|
|
self.kwargs_data = dict()
|
|
|
|
|
self.args_data = list()
|
2024-05-31 22:42:04 +08:00
|
|
|
|
self.matcher: Matcher = None
|
|
|
|
|
self.end = False
|
|
|
|
|
|
|
|
|
|
self.sub_tasks: list[asyncio.Task] = list()
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
2024-05-31 22:42:04 +08:00
|
|
|
|
async def __call__(self, *args, **kwargs):
|
2024-05-31 22:59:02 +08:00
|
|
|
|
self.kwargs_data.update(kwargs)
|
|
|
|
|
self.args_data = list(set(self.args_data + list(args)))
|
2024-05-31 22:42:04 +08:00
|
|
|
|
for i, cmd in enumerate(self.functions):
|
|
|
|
|
r = await self.execute_line(cmd, i, *args, **kwargs)
|
|
|
|
|
if r == 0:
|
|
|
|
|
msg = f"End function {self.name} by line {i}"
|
|
|
|
|
nonebot.logger.debug(msg)
|
|
|
|
|
for task in self.sub_tasks:
|
|
|
|
|
task.cancel(msg)
|
|
|
|
|
return
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
def __str__(self):
|
2024-05-31 22:42:04 +08:00
|
|
|
|
return f"LiteyukiFunction({self.name})"
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
|
return self.__str__()
|
|
|
|
|
|
2024-05-31 22:42:04 +08:00
|
|
|
|
async def execute_line(self, cmd: str, line: int = 0, *args, **kwargs) -> Any:
|
2024-05-31 19:17:25 +08:00
|
|
|
|
"""
|
|
|
|
|
解析一行轻雪函数
|
|
|
|
|
Args:
|
2024-05-31 22:42:04 +08:00
|
|
|
|
cmd: 命令
|
|
|
|
|
line: 行数
|
2024-05-31 19:17:25 +08:00
|
|
|
|
Returns:
|
|
|
|
|
"""
|
2024-06-02 01:32:52 +08:00
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
if "${" in cmd:
|
|
|
|
|
# 此种情况下,{}内容不用管,只对${}内的内容进行format
|
|
|
|
|
for i in range(len(cmd) - 1):
|
|
|
|
|
if cmd[i] == "$" and cmd[i + 1] == "{":
|
|
|
|
|
end = cmd.find("}", i)
|
|
|
|
|
key = cmd[i + 2:end]
|
|
|
|
|
cmd = cmd.replace(f"${{{key}}}", str(self.kwargs_data.get(key, "")))
|
|
|
|
|
else:
|
|
|
|
|
cmd = cmd.format(*self.args_data, **self.kwargs_data)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
pass
|
|
|
|
|
|
2024-05-31 22:42:04 +08:00
|
|
|
|
no_head = cmd.split(" ", 1)[1] if len(cmd.split(" ")) > 1 else ""
|
|
|
|
|
try:
|
2024-06-02 01:32:52 +08:00
|
|
|
|
head, cmd_args, cmd_kwargs = self.get_args(cmd)
|
2024-05-31 22:42:04 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
error_msg = f"Parsing error in {self.name} at line {line}: {e}"
|
|
|
|
|
nonebot.logger.error(error_msg)
|
|
|
|
|
await self.matcher.send(error_msg)
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
if head == "var":
|
2024-05-31 19:17:25 +08:00
|
|
|
|
# 变量定义
|
2024-06-02 01:32:52 +08:00
|
|
|
|
self.kwargs_data.update(cmd_kwargs)
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
elif head == "cmd":
|
|
|
|
|
# 在当前计算机上执行命令
|
2024-05-31 22:42:04 +08:00
|
|
|
|
os.system(no_head)
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
elif head == "api":
|
|
|
|
|
# 调用Bot API 需要Bot实例
|
2024-06-02 01:32:52 +08:00
|
|
|
|
await self.bot.call_api(cmd_args[1], **cmd_kwargs)
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
elif head == "function":
|
|
|
|
|
# 调用轻雪函数
|
2024-06-02 01:32:52 +08:00
|
|
|
|
func = get_function(cmd_args[1])
|
2024-05-31 22:42:04 +08:00
|
|
|
|
func.bot = self.bot
|
|
|
|
|
func.matcher = self.matcher
|
2024-06-02 01:32:52 +08:00
|
|
|
|
await func(*cmd_args[2:], **cmd_kwargs)
|
2024-05-31 22:42:04 +08:00
|
|
|
|
|
|
|
|
|
elif head == "sleep":
|
|
|
|
|
# 等待一段时间
|
2024-06-02 01:32:52 +08:00
|
|
|
|
await asyncio.sleep(float(cmd_args[1]))
|
2024-05-31 22:42:04 +08:00
|
|
|
|
|
|
|
|
|
elif head == "nohup":
|
|
|
|
|
# 挂起运行
|
|
|
|
|
task = asyncio.create_task(self.execute_line(no_head))
|
|
|
|
|
self.sub_tasks.append(task)
|
|
|
|
|
|
|
|
|
|
elif head == "end":
|
|
|
|
|
# 结束所有函数
|
|
|
|
|
self.end = True
|
|
|
|
|
return 0
|
|
|
|
|
|
2024-06-02 01:32:52 +08:00
|
|
|
|
|
2024-05-31 22:42:04 +08:00
|
|
|
|
elif head == "await":
|
|
|
|
|
# 等待所有协程执行完毕
|
|
|
|
|
await asyncio.gather(*self.sub_tasks)
|
|
|
|
|
|
|
|
|
|
def get_args(self, line: str) -> tuple[str, tuple[str, ...], dict[str, Any]]:
|
|
|
|
|
"""
|
|
|
|
|
获取参数
|
|
|
|
|
Args:
|
|
|
|
|
line: 命令
|
|
|
|
|
Returns:
|
|
|
|
|
命令头 参数 关键字
|
|
|
|
|
"""
|
|
|
|
|
line = line.replace("\\=", "EQUAL_SIGN")
|
|
|
|
|
head = ""
|
|
|
|
|
args = list()
|
|
|
|
|
kwargs = dict()
|
|
|
|
|
for i, arg in enumerate(line.split(" ")):
|
|
|
|
|
if "=" in arg:
|
|
|
|
|
key, value = arg.split("=", 1)
|
|
|
|
|
value = value.replace("EQUAL_SIGN", "=")
|
|
|
|
|
try:
|
|
|
|
|
value = eval(value)
|
|
|
|
|
except:
|
2024-05-31 22:59:02 +08:00
|
|
|
|
value = self.kwargs_data.get(value, value)
|
2024-05-31 22:42:04 +08:00
|
|
|
|
kwargs[key] = value
|
|
|
|
|
else:
|
|
|
|
|
if i == 0:
|
|
|
|
|
head = arg
|
|
|
|
|
args.append(arg)
|
|
|
|
|
return head, tuple(args), kwargs
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_function(name: str) -> LiteyukiFunction | None:
|
|
|
|
|
"""
|
|
|
|
|
获取一个轻雪函数
|
|
|
|
|
Args:
|
|
|
|
|
name: 函数名
|
|
|
|
|
Returns:
|
|
|
|
|
"""
|
|
|
|
|
return loaded_functions.get(name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_from_dir(path: str):
|
|
|
|
|
"""
|
2024-05-31 22:42:04 +08:00
|
|
|
|
从目录及其子目录中递归加载所有轻雪函数,类似mcfunction
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
path: 目录路径
|
|
|
|
|
"""
|
|
|
|
|
for f in os.listdir(path):
|
|
|
|
|
f = os.path.join(path, f)
|
|
|
|
|
if os.path.isfile(f):
|
|
|
|
|
if f.endswith(ly_function_extensions):
|
|
|
|
|
load_from_file(f)
|
2024-05-31 22:42:04 +08:00
|
|
|
|
if os.path.isdir(f):
|
|
|
|
|
load_from_dir(f)
|
2024-05-31 19:17:25 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_from_file(path: str):
|
|
|
|
|
"""
|
|
|
|
|
从文件中加载轻雪函数
|
|
|
|
|
Args:
|
|
|
|
|
path:
|
|
|
|
|
Returns:
|
|
|
|
|
"""
|
2024-05-31 22:42:04 +08:00
|
|
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
|
|
|
name = ".".join(os.path.basename(path).split(".")[:-1])
|
|
|
|
|
func = LiteyukiFunction(name)
|
|
|
|
|
for i, line in enumerate(f.read().split("\n")):
|
|
|
|
|
if line.startswith("#") or line.strip() == "":
|
|
|
|
|
continue
|
|
|
|
|
func.functions.append(line)
|
|
|
|
|
loaded_functions[name] = func
|
|
|
|
|
nonebot.logger.debug(f"Loaded function {name}")
|