Adjust expression-related APIs

This commit is contained in:
Richard Chien 2018-12-22 12:44:10 +08:00
parent 07ac7c44e0
commit 6fff0985ae
5 changed files with 33 additions and 47 deletions

View File

@ -6,13 +6,12 @@ from typing import (
)
from . import NoneBot, permission as perm
from .expression import render
from .helpers import context_id, send_expr
from .helpers import context_id, send, render_expression
from .log import logger
from .message import Message
from .session import BaseSession
from .typing import (
Context_T, CommandName_T, CommandArgs_T, Expression_T, Message_T
Context_T, CommandName_T, CommandArgs_T, Message_T
)
# Key: str (one segment of command name)
@ -267,8 +266,7 @@ class CommandSession(BaseSession):
return True
def get(self, key: Any, *,
prompt: Optional[Message_T] = None,
prompt_expr: Optional[Expression_T] = None) -> Any:
prompt: Optional[Message_T] = None) -> Any:
"""
Get an argument with a given key.
@ -279,7 +277,6 @@ class CommandSession(BaseSession):
:param key: argument key
:param prompt: prompt to ask the user
:param prompt_expr: prompt expression to ask the user
:return: the argument value
"""
value = self.get_optional(key)
@ -288,8 +285,6 @@ class CommandSession(BaseSession):
self.current_key = key
# ask the user for more information
if prompt_expr is not None:
prompt = render(prompt_expr, key=key)
self.pause(prompt)
def get_optional(self, key: Any,
@ -436,8 +431,10 @@ async def handle_command(bot: NoneBot, ctx: Context_T) -> bool:
if session.running:
logger.warning(f'There is a session of command '
f'{session.cmd.name} running, notify the user')
asyncio.ensure_future(
send_expr(bot, ctx, bot.config.SESSION_RUNNING_EXPRESSION))
asyncio.ensure_future(send(
bot, ctx,
render_expression(bot.config.SESSION_RUNNING_EXPRESSION)
))
# pretend we are successful, so that NLP won't handle it
return True

View File

@ -17,7 +17,7 @@ For example:
from datetime import timedelta
from typing import Container, Union, Iterable, Pattern, Optional, Dict, Any
from .expression import Expression_T
from .typing import Expression_T
API_ROOT: str = ''
ACCESS_TOKEN: str = ''

View File

@ -1,25 +0,0 @@
import random
from typing import Sequence, Callable
from .message import escape
from .typing import Expression_T
def render(expr: Expression_T, *, escape_args: bool = True, **kwargs) -> str:
"""
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
"""
if isinstance(expr, Callable):
expr = expr(**kwargs)
elif isinstance(expr, Sequence) and not isinstance(expr, str):
expr = random.choice(expr)
if escape_args:
for k, v in kwargs.items():
if isinstance(v, str):
kwargs[k] = escape(v)
return expr.format(**kwargs)

View File

@ -1,7 +1,10 @@
import hashlib
import random
from typing import Sequence, Callable
from . import NoneBot, expression
from . import NoneBot
from .exceptions import CQHttpError
from .message import escape
from .typing import Context_T, Message_T, Expression_T
@ -62,7 +65,22 @@ async def send(bot: NoneBot, ctx: Context_T, message: Message_T, *,
raise
async def send_expr(bot: NoneBot, ctx: Context_T,
expr: Expression_T, **kwargs):
"""Sending a expression message ignoring failure by default."""
return await send(bot, ctx, expression.render(expr, **kwargs))
def render_expression(expr: Expression_T, *,
escape_args: bool = True, **kwargs) -> str:
"""
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
"""
if isinstance(expr, Callable):
expr = expr(**kwargs)
elif isinstance(expr, Sequence) and not isinstance(expr, str):
expr = random.choice(expr)
if escape_args:
for k, v in kwargs.items():
if isinstance(v, str):
kwargs[k] = escape(v)
return expr.format(**kwargs)

View File

@ -1,6 +1,6 @@
from . import NoneBot
from .helpers import send, send_expr
from .typing import Context_T, Message_T, Expression_T
from .helpers import send
from .typing import Context_T, Message_T
class BaseSession:
@ -15,7 +15,3 @@ class BaseSession:
"""Send a message ignoring failure by default."""
return await send(self.bot, self.ctx, message,
ignore_failure=ignore_failure)
async def send_expr(self, expr: Expression_T, **kwargs):
"""Sending a expression message ignoring failure by default."""
return await send_expr(self.bot, self.ctx, expr, **kwargs)