Improve message sending APIs

This commit is contained in:
Richard Chien 2018-12-23 20:20:40 +08:00
parent 7cb634c77a
commit 7dff9f7fd5
4 changed files with 35 additions and 22 deletions

View File

@ -4,6 +4,11 @@ sidebar: auto
# 更新日志 # 更新日志
## next
- 给所有发送消息的函数和方法(`BaseSession.send()`、`CommandSession.pause()`、`CommandSession.finish()` 等)新增了 `**kwargs`,并将此参数继续传递给 python-aiocqhttp 的 `CQHttp.send()` 方法,从而支持 `at_sender` 参数(默认 `False`
- `BaseSession.send()` 方法新增 `ensure_private` 参数,类型 `bool`,默认 `False`,可用于确保发送消息到私聊(对于群消息,会私聊发送给发送人)
## v0.5.0 ## v0.5.0
- 修复调用不存在的多级命令(例如 `/echo/nonexist`)时,抛出异常导致 WebSocket 连接断开的问题 - 修复调用不存在的多级命令(例如 `/echo/nonexist`)时,抛出异常导致 WebSocket 连接断开的问题

View File

@ -307,7 +307,7 @@ class CommandSession(BaseSession):
if s.type == 'image' and 'url' in s.data] if s.type == 'image' and 'url' in s.data]
def get(self, key: Any, *, def get(self, key: Any, *,
prompt: Optional[Message_T] = None) -> Any: prompt: Optional[Message_T] = None, **kwargs) -> Any:
""" """
Get an argument with a given key. Get an argument with a given key.
@ -326,23 +326,23 @@ class CommandSession(BaseSession):
self.current_key = key self.current_key = key
# ask the user for more information # ask the user for more information
self.pause(prompt) self.pause(prompt, **kwargs)
def get_optional(self, key: Any, def get_optional(self, key: Any,
default: Optional[Any] = None) -> Optional[Any]: default: Optional[Any] = None) -> Optional[Any]:
"""Simply get a argument with given key.""" """Simply get a argument with given key."""
return self.args.get(key, default) return self.args.get(key, default)
def pause(self, message: Optional[Message_T] = None) -> None: def pause(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Pause the session for further interaction.""" """Pause the session for further interaction."""
if message: if message:
asyncio.ensure_future(self.send(message)) asyncio.ensure_future(self.send(message, **kwargs))
raise _FurtherInteractionNeeded raise _FurtherInteractionNeeded
def finish(self, message: Optional[Message_T] = None) -> None: def finish(self, message: Optional[Message_T] = None, **kwargs) -> None:
"""Finish the session.""" """Finish the session."""
if message: if message:
asyncio.ensure_future(self.send(message)) asyncio.ensure_future(self.send(message, **kwargs))
raise _FinishException raise _FinishException
def switch(self, new_ctx_message: Message_T) -> None: def switch(self, new_ctx_message: Message_T) -> None:

View File

@ -44,22 +44,17 @@ def context_id(ctx: Context_T, *,
return ctx_id return ctx_id
async def send(bot: NoneBot, ctx: Context_T, message: Message_T, *, async def send(bot: NoneBot, ctx: Context_T,
ignore_failure: bool = True) -> None: message: Message_T, *,
ensure_private: bool = False,
ignore_failure: bool = True,
**kwargs) -> None:
"""Send a message ignoring failure by default.""" """Send a message ignoring failure by default."""
try: try:
if ctx.get('post_type') == 'message': if ensure_private:
await bot.send(ctx, message)
else:
ctx = ctx.copy() ctx = ctx.copy()
if 'message' in ctx: ctx['message_type'] = 'private'
del ctx['message'] await bot.send(ctx, message, **kwargs)
if 'group_id' in ctx:
await bot.send_group_msg(**ctx, message=message)
elif 'discuss_id' in ctx:
await bot.send_discuss_msg(**ctx, message=message)
elif 'user_id' in ctx:
await bot.send_private_msg(**ctx, message=message)
except CQHttpError: except CQHttpError:
if not ignore_failure: if not ignore_failure:
raise raise

View File

@ -11,7 +11,20 @@ class BaseSession:
self.ctx = ctx self.ctx = ctx
async def send(self, message: Message_T, *, async def send(self, message: Message_T, *,
ignore_failure: bool = True) -> None: at_sender: bool = False,
"""Send a message ignoring failure by default.""" ensure_private: bool = False,
ignore_failure: bool = True,
**kwargs) -> None:
"""
Send a message ignoring failure by default.
:param message: message to send
:param at_sender: @ the sender if in group or discuss chat
:param ensure_private: ensure the message is sent to private chat
:param ignore_failure: if any CQHttpError raised, ignore it
:return: the result returned by CQHTTP
"""
return await send(self.bot, self.ctx, message, return await send(self.bot, self.ctx, message,
ignore_failure=ignore_failure) at_sender=at_sender,
ensure_private=ensure_private,
ignore_failure=ignore_failure, **kwargs)