diff --git a/nonebot/adapters/_base.py b/nonebot/adapters/_base.py index 30fa312a..223dea6d 100644 --- a/nonebot/adapters/_base.py +++ b/nonebot/adapters/_base.py @@ -333,6 +333,28 @@ class Message(List[TMS], abc.ABC): @classmethod def template(cls: Type[TM], format_string: str) -> MessageFormatter[TM]: + """ + :说明: + + 根据创建消息模板, 用法和 ``str.format`` 大致相同, 但是可以输出消息对象 + + :示例: + + .. code-block:: python + + >>> Message.template("{} {}").format("hello", "world") + Message(MessageSegment(type='text', data={'text': 'hello world'})) + >>> Message.template("{} {}").format(MessageSegment.image("file///..."), "world") + Message(MessageSegment(type='image', data={'file': 'file///...'}), MessageSegment(type='text', data={'text': 'world'})) + + :参数: + + * ``format_string: str``: 格式化字符串 + + :返回: + + - ``MessageFormatter[TM]``: 消息格式化器 + """ return MessageFormatter(cls, format_string) @classmethod diff --git a/nonebot/adapters/_formatter.py b/nonebot/adapters/_formatter.py index 9dad44d1..68994f42 100644 --- a/nonebot/adapters/_formatter.py +++ b/nonebot/adapters/_formatter.py @@ -11,12 +11,18 @@ TM = TypeVar("TM", bound="Message") class MessageFormatter(Formatter, Generic[TM]): + """消息模板格式化实现类""" def __init__(self, factory: Type[TM], template: str) -> None: self.template = template self.factory = factory def format(self, *args: Any, **kwargs: Any) -> TM: + """ + :说明: + + 根据模板和参数生成消息对象 + """ msg = self.vformat(self.template, args, kwargs) return msg if isinstance(msg, self.factory) else self.factory(msg)