mirror of
https://github.com/nonebot/nonebot2.git
synced 2024-11-28 03:05:25 +08:00
💡 add comment to describe template formatter usage
This commit is contained in:
parent
7cfdc2dd37
commit
1c73a9adfa
@ -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
|
||||
|
@ -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)
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user