nonebot2/nonebot/message.py

91 lines
2.7 KiB
Python
Raw Normal View History

2020-07-04 22:51:10 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2020-07-25 12:28:30 +08:00
import asyncio
2020-08-06 17:54:55 +08:00
from datetime import datetime
2020-07-25 12:28:30 +08:00
2020-07-05 20:39:34 +08:00
from nonebot.log import logger
2020-08-17 16:09:41 +08:00
from nonebot.rule import TrieRule
2020-07-05 20:39:34 +08:00
from nonebot.matcher import matchers
from nonebot.typing import Set, Type, Union, NoReturn
from nonebot.typing import Bot, Event, Matcher, PreProcessor
from nonebot.exception import IgnoredException, ExpiredException
from nonebot.exception import StopPropagation, _ExceptionContainer
2020-07-25 12:28:30 +08:00
2020-08-10 13:06:02 +08:00
_event_preprocessors: Set[PreProcessor] = set()
2020-07-25 12:28:30 +08:00
2020-08-10 13:06:02 +08:00
def event_preprocessor(func: PreProcessor) -> PreProcessor:
2020-07-25 12:28:30 +08:00
_event_preprocessors.add(func)
return func
2020-07-04 22:51:10 +08:00
async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event,
state: dict) -> Union[None, NoReturn]:
2020-08-24 17:59:36 +08:00
if Matcher.expire_time and datetime.now() > Matcher.expire_time:
raise _ExceptionContainer([ExpiredException])
try:
if not await Matcher.check_perm(
bot, event) or not await Matcher.check_rule(bot, event, state):
return
except Exception as e:
logger.error(f"Rule check failed for matcher {Matcher}. Ignored.")
logger.exception(e)
return
matcher = Matcher()
# TODO: BeforeMatcherRun
try:
logger.debug(f"Running matcher {matcher}")
await matcher.run(bot, event, state)
except Exception as e:
logger.error(f"Running matcher {matcher} failed.")
logger.exception(e)
exceptions = []
if Matcher.temp:
exceptions.append(ExpiredException)
if Matcher.block:
exceptions.append(StopPropagation)
if exceptions:
raise _ExceptionContainer(exceptions)
2020-08-10 13:06:02 +08:00
async def handle_event(bot: Bot, event: Event):
2020-07-25 12:28:30 +08:00
coros = []
2020-08-17 16:09:41 +08:00
state = {}
2020-07-25 12:28:30 +08:00
for preprocessor in _event_preprocessors:
2020-08-17 16:09:41 +08:00
coros.append(preprocessor(bot, event, state))
2020-07-25 12:28:30 +08:00
if coros:
try:
await asyncio.gather(*coros)
except IgnoredException:
logger.info(f"Event {event} is ignored")
return
2020-07-04 22:51:10 +08:00
2020-08-17 16:09:41 +08:00
# Trie Match
2020-08-24 17:59:36 +08:00
_, _ = TrieRule.get_value(bot, event, state)
2020-08-17 16:09:41 +08:00
break_flag = False
2020-07-04 22:51:10 +08:00
for priority in sorted(matchers.keys()):
if break_flag:
break
pending_tasks = [
_run_matcher(matcher, bot, event, state.copy())
for matcher in matchers[priority]
]
results = await asyncio.gather(*pending_tasks, return_exceptions=True)
i = 0
for index, result in enumerate(results):
if isinstance(result, _ExceptionContainer):
e_list = result.exceptions
if StopPropagation in e_list:
break_flag = True
if ExpiredException in e_list:
del matchers[priority][index - i]
i += 1