nonebot2/none/message.py

69 lines
2.0 KiB
Python
Raw Normal View History

2018-07-30 15:41:19 +00:00
import asyncio
2018-10-14 11:54:55 +00:00
from typing import Callable
2018-06-14 22:58:24 +00:00
2018-10-14 11:54:55 +00:00
from aiocqhttp.message import *
2018-06-14 22:58:24 +00:00
2018-07-04 01:28:31 +00:00
from . import NoneBot
2018-07-24 15:59:45 +00:00
from .command import handle_command, SwitchException
2018-06-27 14:50:01 +00:00
from .log import logger
2018-07-02 08:54:29 +00:00
from .natural_language import handle_natural_language
2018-10-15 17:03:50 +00:00
from .typing import Context_T
2018-06-14 22:58:24 +00:00
2018-07-30 15:41:19 +00:00
_message_preprocessors = set()
def message_preprocessor(func: Callable) -> Callable:
_message_preprocessors.add(func)
return func
2018-06-27 08:36:40 +00:00
2018-10-15 17:03:50 +00:00
async def handle_message(bot: NoneBot, ctx: Context_T) -> None:
2018-07-20 16:46:34 +00:00
_log_message(ctx)
2018-07-30 15:41:19 +00:00
coros = []
for processor in _message_preprocessors:
2018-10-15 17:03:50 +00:00
coros.append(processor(bot, ctx))
2018-07-30 15:41:19 +00:00
if coros:
await asyncio.wait(coros)
2018-12-22 12:21:31 +00:00
if 'to_me' not in ctx:
if ctx['message_type'] != 'private':
# group or discuss
ctx['to_me'] = False
first_message_seg = ctx['message'][0]
if first_message_seg == MessageSegment.at(ctx['self_id']):
ctx['to_me'] = True
del ctx['message'][0]
if not ctx['message']:
ctx['message'].append(MessageSegment.text(''))
else:
ctx['to_me'] = True
2018-06-14 22:58:24 +00:00
2018-07-24 15:59:45 +00:00
while True:
try:
handled = await handle_command(bot, ctx)
break
except SwitchException as e:
# we are sure that there is no session existing now
ctx['message'] = e.new_ctx_message
ctx['to_me'] = True
2018-06-14 22:58:24 +00:00
if handled:
2018-07-20 16:46:34 +00:00
logger.info(f'Message {ctx["message_id"]} is handled as a command')
2018-06-27 08:36:40 +00:00
return
2018-06-30 02:58:56 +00:00
2018-07-01 03:01:24 +00:00
handled = await handle_natural_language(bot, ctx)
if handled:
2018-07-20 16:46:34 +00:00
logger.info(f'Message {ctx["message_id"]} is handled '
f'as natural language')
2018-07-01 03:01:24 +00:00
return
2018-07-20 16:46:34 +00:00
2018-10-15 17:03:50 +00:00
def _log_message(ctx: Context_T) -> None:
2018-07-20 16:46:34 +00:00
msg_from = f'{ctx["user_id"]}'
if ctx['message_type'] == 'group':
msg_from += f'@[群:{ctx["group_id"]}]'
elif ctx['message_type'] == 'discuss':
msg_from += f'@[讨论组:{ctx["discuss_id"]}]'
logger.info(f'Message {ctx["message_id"]} from {msg_from}: '
f'{ctx["message"]}')