2018-06-25 21:14:27 +08:00
|
|
|
import random
|
2018-10-16 01:03:50 +08:00
|
|
|
from typing import Sequence, Callable
|
2018-06-25 21:14:27 +08:00
|
|
|
|
2018-10-14 22:52:37 +08:00
|
|
|
from .message import escape
|
2018-10-16 01:03:50 +08:00
|
|
|
from .typing import Expression_T
|
2018-06-25 21:14:27 +08:00
|
|
|
|
|
|
|
|
2018-10-16 01:03:50 +08:00
|
|
|
def render(expr: Expression_T, *, escape_args: bool = True, **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)
|