2018-06-27 22:50:01 +08:00
|
|
|
from typing import Dict, Any, Union, List, Sequence, Callable
|
2018-06-27 22:05:12 +08:00
|
|
|
|
2018-07-04 09:28:31 +08:00
|
|
|
from aiocqhttp import Error as CQHttpError
|
2018-06-27 22:05:12 +08:00
|
|
|
|
2018-07-04 09:28:31 +08:00
|
|
|
from . import NoneBot, expression
|
2018-06-15 06:58:24 +08:00
|
|
|
|
|
|
|
|
2018-07-01 20:01:05 +08:00
|
|
|
def context_id(ctx: Dict[str, Any]) -> str:
|
|
|
|
"""
|
|
|
|
Calculate a unique id representing the current user.
|
|
|
|
"""
|
2018-06-15 06:58:24 +08:00
|
|
|
src = ''
|
|
|
|
if ctx.get('group_id'):
|
2018-06-25 15:22:59 +08:00
|
|
|
src += f'/group/{ctx["group_id"]}'
|
2018-06-15 06:58:24 +08:00
|
|
|
elif ctx.get('discuss_id'):
|
2018-06-25 15:22:59 +08:00
|
|
|
src += f'/discuss/{ctx["discuss_id"]}'
|
2018-06-15 06:58:24 +08:00
|
|
|
if ctx.get('user_id'):
|
2018-06-25 15:22:59 +08:00
|
|
|
src += f'/user/{ctx["user_id"]}'
|
2018-06-15 06:58:24 +08:00
|
|
|
return src
|
2018-06-27 22:05:12 +08:00
|
|
|
|
|
|
|
|
2018-07-04 09:28:31 +08:00
|
|
|
async def send(bot: NoneBot, ctx: Dict[str, Any],
|
2018-06-27 22:05:12 +08:00
|
|
|
message: Union[str, Dict[str, Any], List[Dict[str, Any]]],
|
|
|
|
*, ignore_failure: bool = True) -> None:
|
2018-07-01 20:01:05 +08:00
|
|
|
"""
|
|
|
|
Send a message ignoring failure by default.
|
|
|
|
"""
|
2018-06-27 22:05:12 +08:00
|
|
|
try:
|
|
|
|
if ctx.get('post_type') == 'message':
|
|
|
|
await bot.send(ctx, message)
|
|
|
|
else:
|
|
|
|
ctx = ctx.copy()
|
|
|
|
if 'message' in ctx:
|
|
|
|
del ctx['message']
|
|
|
|
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:
|
|
|
|
if not ignore_failure:
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
2018-07-04 09:28:31 +08:00
|
|
|
async def send_expr(bot: NoneBot, ctx: Dict[str, Any],
|
2018-06-27 22:05:12 +08:00
|
|
|
expr: Union[str, Sequence[str], Callable],
|
|
|
|
**kwargs):
|
2018-07-01 20:01:05 +08:00
|
|
|
"""
|
|
|
|
Sending a expression message ignoring failure by default.
|
|
|
|
"""
|
2018-06-27 22:05:12 +08:00
|
|
|
return await send(bot, ctx, expression.render(expr, **kwargs))
|