2018-06-25 21:14:27 +08:00
|
|
|
import random
|
|
|
|
from typing import Union, Sequence, Callable
|
|
|
|
|
2018-10-14 22:52:37 +08:00
|
|
|
from .message import escape
|
2018-06-25 21:14:27 +08:00
|
|
|
|
2018-10-14 20:32:00 +08:00
|
|
|
Expression_T = Union[str, Sequence[str], Callable]
|
2018-06-25 21:14:27 +08:00
|
|
|
|
2018-10-14 20:32:00 +08:00
|
|
|
|
|
|
|
def render(expr: Expression_T, *, 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):
|
2018-10-14 22:52:37 +08:00
|
|
|
kwargs[k] = escape(v)
|
2018-06-25 21:14:27 +08:00
|
|
|
return expr.format(**kwargs)
|