2018-06-25 21:14:27 +08:00
|
|
|
import random
|
|
|
|
from typing import Union, Sequence, Callable
|
|
|
|
|
|
|
|
from aiocqhttp import message
|
|
|
|
|
|
|
|
|
|
|
|
def render(expr: Union[str, Sequence[str], Callable], *, escape_args=True,
|
2018-06-26 08:49:08 +08:00
|
|
|
**kwargs) -> str:
|
2018-07-01 20:01:05 +08:00
|
|
|
"""
|
|
|
|
Render an expression to message string.
|
|
|
|
|
|
|
|
:param expr: expression to render
|
|
|
|
:param escape_args: should escape arguments or not
|
|
|
|
:param kwargs: keyword arguments used in str.format()
|
|
|
|
:return: the rendered message
|
|
|
|
"""
|
2018-06-25 21:14:27 +08:00
|
|
|
if isinstance(expr, Callable):
|
2018-07-25 23:02:43 +08:00
|
|
|
expr = expr(**kwargs)
|
2018-07-21 23:51:50 +08:00
|
|
|
elif isinstance(expr, Sequence) and not isinstance(expr, str):
|
2018-06-25 21:14:27 +08:00
|
|
|
expr = random.choice(expr)
|
|
|
|
if escape_args:
|
|
|
|
for k, v in kwargs.items():
|
|
|
|
if isinstance(v, str):
|
|
|
|
kwargs[k] = message.escape(v)
|
|
|
|
return expr.format(**kwargs)
|