Skip to content

Commit

Permalink
🔖 version 0.35.1
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Jan 2, 2024
1 parent e81ca45 commit bc4d5df
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 43 deletions.
2 changes: 1 addition & 1 deletion src/nonebot_plugin_alconna/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
from .consts import ALCONNA_EXEC_RESULT as ALCONNA_EXEC_RESULT
from .extension import add_global_extension as add_global_extension

__version__ = "0.35.0"
__version__ = "0.35.1"

__plugin_meta__ = PluginMetadata(
name="Alconna 插件",
Expand Down
2 changes: 1 addition & 1 deletion src/nonebot_plugin_alconna/uniseg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from .params import UniversalMessage as UniversalMessage
from .params import UniversalSegment as UniversalSegment

__version__ = "0.35.0"
__version__ = "0.35.1"

__plugin_meta__ = PluginMetadata(
name="Universal Segment 插件",
Expand Down
80 changes: 40 additions & 40 deletions src/nonebot_plugin_alconna/uniseg/template.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import re
import functools
import _string # type: ignore
from string import Formatter
from typing_extensions import TypeAlias
from typing import (
Expand All @@ -19,6 +18,7 @@
cast,
)

import _string # type: ignore
from tarina.tools import gen_subclass

from .segment import Segment
Expand All @@ -33,6 +33,43 @@
_PATTERN = re.compile("(" + "|".join(_MAPPING.keys()) + r")\((.*)\)$")


def _eval(route: str, obj: Any):
res = obj
parts = re.split(r"\.|(\[.+\])|(\(.*\))", route)
for part in parts[1:]:
if not part:
continue
if part.startswith("_"):
raise ValueError(route)
if part.startswith("[") and part.endswith("]"):
item = part[1:-1]
if item[0] in ("'", '"') and item[-1] in ("'", '"'):
res = res[item[1:-1]]
elif ":" in item:
res = res[slice(*(int(x) if x else None for x in item.split(":")))]
else:
res = res[int(item)]
elif part.startswith("(") and part.endswith(")"):
item = part[1:-1]
if not item:
res = res()
else:
_parts = item.split(",")
_args = []
_kwargs = {}
for part in _parts:
part = part.strip()
if re.match(".+=.+", part):
k, v = part.split("=")
_kwargs[k] = v
else:
_args.append(part)
res = res(*_args, **_kwargs)
else:
res = getattr(res, part)
return res


class UniMessageTemplate(Formatter):
"""通用消息模板格式化实现类。
Expand Down Expand Up @@ -103,43 +140,6 @@ def _format(self, args: Sequence[Any], kwargs: Mapping[str, Any]):
# f"not all arguments converted during string formatting: " f"{set(kwargs) - set(keys)}"
# )

def _getattr(self, route: str, obj: Any):
res = obj
parts = re.split(r"\.|(\[.+\])|(\(.*\))", route)
for part in parts[1:]:
if not part:
continue
if part.startswith("_"):
raise ValueError(route)
if part.startswith("[") and part.endswith("]"):
item = part[1:-1]
if item[0] in ("'", '"') and item[-1] in ("'", '"'):
res = res[item[1:-1]]
elif ":" in item:
res = res[slice(*map(lambda x: int(x) if x else None, item.split(':')))]
else:
res = res[int(item)]
elif part.startswith("(") and part.endswith(")"):
item = part[1:-1]
if not item:
res = res()
else:
_parts = item.split(",")
_args = []
_kwargs = {}
for part in _parts:
part = part.strip()
if re.match(".+=.+", part):
k, v = part.split("=")
_kwargs[k] = v
else:
_args.append(part)
res = res(*_args, **_kwargs)
else:
res = getattr(res, part)
return res


def _vformat(
self,
format_string: str,
Expand All @@ -164,14 +164,14 @@ def _vformat(
for part in parts:
part = part.strip()
if part.startswith("$") and (key := part.split(".")[0]) in kwargs:
_args.append(self._getattr(part[1:], kwargs[key]))
_args.append(_eval(part[1:], kwargs[key]))
elif re.match(".+=.+", part):
k, v = part.split("=")
if v in kwargs:
_kwargs[k] = kwargs[v]
used_args.add(v)
elif v.startswith("$") and (key := v.split(".")[0]) in kwargs:
_kwargs[k] = self._getattr(v[1:], kwargs[key])
_kwargs[k] = _eval(v[1:], kwargs[key])
else:
_kwargs[k] = v
elif part in kwargs:
Expand Down
4 changes: 3 additions & 1 deletion tests/test_uniseg.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ async def test_unimsg_template(app: App):

@matcher.handle()
async def handle():
await matcher.finish(UniMessage.template("{:Reply($message_id)}{:At(user, $event.get_user_id()[1:])}"))
await matcher.finish(
UniMessage.template("{:Reply($message_id)}{:At(user, $event.get_user_id()[1:])}")
)

async with app.test_matcher(matcher) as ctx:
adapter = get_adapter(Adapter)
Expand Down

0 comments on commit bc4d5df

Please sign in to comment.