2020-09-30 18:01:31 +08:00
|
|
|
import re
|
2020-08-10 13:06:02 +08:00
|
|
|
import json
|
2020-08-14 17:41:24 +08:00
|
|
|
import asyncio
|
2020-08-10 13:06:02 +08:00
|
|
|
import dataclasses
|
2020-08-14 17:41:24 +08:00
|
|
|
from functools import wraps, partial
|
2020-08-10 13:06:02 +08:00
|
|
|
|
2020-08-14 17:41:24 +08:00
|
|
|
from nonebot.typing import Any, Callable, Awaitable, overrides
|
|
|
|
|
|
|
|
|
2020-09-30 18:01:31 +08:00
|
|
|
def escape_tag(s: str) -> str:
|
2020-10-01 00:39:44 +08:00
|
|
|
"""
|
|
|
|
:说明:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-10-01 00:55:03 +08:00
|
|
|
用于记录带颜色日志时转义 ``<tag>`` 类型特殊标签
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-10-01 00:39:44 +08:00
|
|
|
:参数:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-10-01 00:39:44 +08:00
|
|
|
* ``s: str``: 需要转义的字符串
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-10-01 00:39:44 +08:00
|
|
|
:返回:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-10-01 00:39:44 +08:00
|
|
|
- ``str``
|
|
|
|
"""
|
2020-09-30 18:01:31 +08:00
|
|
|
return re.sub(r"</?((?:[fb]g\s)?[^<>\s]*)>", r"\\\g<0>", s)
|
|
|
|
|
|
|
|
|
2020-08-14 17:41:24 +08:00
|
|
|
def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]:
|
2020-09-13 00:43:31 +08:00
|
|
|
"""
|
|
|
|
:说明:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 00:43:31 +08:00
|
|
|
一个用于包装 sync function 为 async function 的装饰器
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 00:43:31 +08:00
|
|
|
:参数:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 00:43:31 +08:00
|
|
|
* ``func: Callable[..., Any]``: 被装饰的同步函数
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 00:43:31 +08:00
|
|
|
:返回:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 13:01:23 +08:00
|
|
|
- ``Callable[..., Awaitable[Any]]``
|
2020-09-13 00:43:31 +08:00
|
|
|
"""
|
2020-08-14 17:41:24 +08:00
|
|
|
|
|
|
|
@wraps(func)
|
|
|
|
async def _wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
|
|
loop = asyncio.get_running_loop()
|
|
|
|
pfunc = partial(func, *args, **kwargs)
|
|
|
|
result = await loop.run_in_executor(None, pfunc)
|
|
|
|
return result
|
|
|
|
|
|
|
|
return _wrapper
|
2020-08-10 13:06:02 +08:00
|
|
|
|
|
|
|
|
|
|
|
class DataclassEncoder(json.JSONEncoder):
|
2020-09-13 00:43:31 +08:00
|
|
|
"""
|
|
|
|
:说明:
|
2020-11-30 11:08:00 +08:00
|
|
|
|
2020-09-13 13:01:23 +08:00
|
|
|
在JSON序列化 ``Message`` (List[Dataclass]) 时使用的 ``JSONEncoder``
|
2020-09-13 00:43:31 +08:00
|
|
|
"""
|
2020-08-10 13:06:02 +08:00
|
|
|
|
|
|
|
@overrides(json.JSONEncoder)
|
|
|
|
def default(self, o):
|
|
|
|
if dataclasses.is_dataclass(o):
|
|
|
|
return dataclasses.asdict(o)
|
|
|
|
return super().default(o)
|