nonebot2/nonebot/message.py

269 lines
8.2 KiB
Python
Raw Normal View History

2020-11-13 17:15:45 +08:00
"""
事件处理
========
2020-11-16 15:06:37 +08:00
NoneBot 内部处理并按优先级分发事件给所有事件响应器提供了多个插槽以进行事件的预处理等
2020-11-13 17:15:45 +08:00
"""
2020-07-25 12:28:30 +08:00
import asyncio
2020-08-06 17:54:55 +08:00
from datetime import datetime
2020-12-06 02:30:19 +08:00
from typing import Set, Type, Optional, Iterable, TYPE_CHECKING
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-11-16 11:25:42 +08:00
from nonebot.matcher import matchers, Matcher
2020-12-09 17:51:24 +08:00
from nonebot.exception import IgnoredException, StopPropagation, NoLogException
2020-12-17 21:09:30 +08:00
from nonebot.typing import T_State, T_EventPreProcessor, T_RunPreProcessor, T_EventPostProcessor, T_RunPostProcessor
2020-12-06 02:30:19 +08:00
if TYPE_CHECKING:
2020-12-07 00:06:09 +08:00
from nonebot.adapters import Bot, Event
2020-07-25 12:28:30 +08:00
2020-12-17 21:09:30 +08:00
_event_preprocessors: Set[T_EventPreProcessor] = set()
_event_postprocessors: Set[T_EventPostProcessor] = set()
_run_preprocessors: Set[T_RunPreProcessor] = set()
_run_postprocessors: Set[T_RunPostProcessor] = set()
2020-07-25 12:28:30 +08:00
2020-12-17 21:09:30 +08:00
def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor:
2020-11-16 15:06:37 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
事件预处理装饰一个函数使它在每次接收到事件并分发给各响应器之前执行
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
事件预处理函数接收三个参数
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
2020-12-17 21:09:30 +08:00
* ``state: T_State``: 当前 State
2020-11-16 15:06:37 +08:00
"""
2020-07-25 12:28:30 +08:00
_event_preprocessors.add(func)
return func
2020-07-04 22:51:10 +08:00
2020-12-17 21:09:30 +08:00
def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor:
2020-11-16 15:06:37 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
事件后处理装饰一个函数使它在每次接收到事件并分发给各响应器之后执行
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
事件后处理函数接收三个参数
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
2020-12-17 21:09:30 +08:00
* ``state: T_State``: 当前事件运行前 State
2020-11-16 15:06:37 +08:00
"""
_event_postprocessors.add(func)
return func
2020-12-17 21:09:30 +08:00
def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor:
2020-11-16 15:06:37 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
运行预处理装饰一个函数使它在每次事件响应器运行前执行
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
运行预处理函数接收四个参数
* ``matcher: Matcher``: 当前要运行的事件响应器
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
2020-12-17 21:09:30 +08:00
* ``state: T_State``: 当前 State
2020-11-16 15:06:37 +08:00
"""
_run_preprocessors.add(func)
return func
2020-12-17 21:09:30 +08:00
def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor:
2020-11-16 15:06:37 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
运行后处理装饰一个函数使它在每次事件响应器运行后执行
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
运行后处理函数接收五个参数
* ``matcher: Matcher``: 运行完毕的事件响应器
* ``exception: Optional[Exception]``: 事件响应器运行错误如果存在
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
2020-12-17 21:09:30 +08:00
* ``state: T_State``: 当前 State
2020-11-16 15:06:37 +08:00
"""
_run_postprocessors.add(func)
return func
2020-12-06 02:30:19 +08:00
async def _check_matcher(priority: int, bot: "Bot", event: "Event",
2020-12-17 21:09:30 +08:00
state: T_State) -> Iterable[Type[Matcher]]:
2020-11-16 11:25:42 +08:00
current_matchers = matchers[priority].copy()
2020-12-06 02:30:19 +08:00
async def _check(Matcher: Type[Matcher], bot: "Bot", event: "Event",
2020-12-17 21:09:30 +08:00
state: T_State) -> Optional[Type[Matcher]]:
2020-11-16 11:25:42 +08:00
try:
2020-11-19 23:18:03 +08:00
if (not Matcher.expire_time or datetime.now() <= Matcher.expire_time
) and await Matcher.check_perm(
bot, event) and await Matcher.check_rule(bot, event, state):
2020-11-16 11:25:42 +08:00
return Matcher
except Exception as e:
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Rule check failed for {Matcher}.</bg #f8bbd0></r>"
)
return None
async def _check_expire(Matcher: Type[Matcher]) -> Optional[Type[Matcher]]:
if Matcher.temp or (Matcher.expire_time and
datetime.now() > Matcher.expire_time):
return Matcher
return None
checking_tasks = [
_check(Matcher, bot, event, state) for Matcher in current_matchers
]
checking_expire_tasks = [
_check_expire(Matcher) for Matcher in current_matchers
]
results = await asyncio.gather(*checking_tasks, return_exceptions=True)
expired = await asyncio.gather(*checking_expire_tasks)
2020-12-11 16:29:12 +08:00
for expired_matcher in filter(lambda x: x, expired):
2020-11-16 11:25:42 +08:00
try:
2020-12-07 00:52:26 +08:00
matchers[priority].remove(expired_matcher) # type: ignore
2020-11-16 11:25:42 +08:00
except Exception:
pass
2020-11-16 12:35:04 +08:00
return filter(lambda x: x, results)
2020-11-16 11:25:42 +08:00
2020-12-06 02:30:19 +08:00
async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event",
2020-12-17 21:09:30 +08:00
state: T_State) -> None:
2020-08-26 17:47:36 +08:00
logger.info(f"Event will be handled by {Matcher}")
matcher = Matcher()
coros = list(
map(lambda x: x(matcher, bot, event, state), _run_preprocessors))
if coros:
try:
await asyncio.gather(*coros)
except IgnoredException:
logger.opt(colors=True).info(
f"Matcher {matcher} running is <b>cancelled</b>")
return
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running RunPreProcessors. "
"Running cancelled!</bg #f8bbd0></r>")
return
2020-11-16 11:25:42 +08:00
exception = None
try:
logger.debug(f"Running matcher {matcher}")
await matcher.run(bot, event, state)
except StopPropagation as e:
exception = e
except Exception as e:
2020-08-27 16:43:58 +08:00
logger.opt(colors=True, exception=e).error(
f"<r><bg #f8bbd0>Running matcher {matcher} failed.</bg #f8bbd0></r>"
)
2020-11-16 11:25:42 +08:00
exception = e
coros = list(
2020-11-16 11:25:42 +08:00
map(lambda x: x(matcher, exception, bot, event, state),
_run_postprocessors))
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running RunPostProcessors</bg #f8bbd0></r>"
)
if matcher.block or isinstance(exception, StopPropagation):
2020-11-16 11:25:42 +08:00
raise StopPropagation
2020-12-05 20:32:38 +08:00
return
2020-12-06 02:30:19 +08:00
async def handle_event(bot: "Bot", event: "Event"):
2020-11-16 15:06:37 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
处理一个事件调用该函数以实现分发事件
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
* ``bot: Bot``: Bot 对象
* ``event: Event``: Event 对象
2020-11-30 11:08:00 +08:00
2020-11-16 15:06:37 +08:00
:示例:
2020-11-16 19:57:49 +08:00
.. code-block:: python
2020-11-16 15:06:37 +08:00
import asyncio
asyncio.create_task(handle_event(bot, event))
"""
2020-10-29 17:06:07 +08:00
show_log = True
2020-12-09 17:51:24 +08:00
log_msg = f"<m>{bot.type.upper()} {bot.self_id}</m> | "
try:
log_msg += event.get_log_string()
except NoLogException:
2020-10-29 17:06:07 +08:00
show_log = False
if show_log:
logger.opt(colors=True).info(log_msg)
2020-08-25 18:02:18 +08:00
2020-08-17 16:09:41 +08:00
state = {}
coros = list(map(lambda x: x(bot, event, state), _event_preprocessors))
2020-07-25 12:28:30 +08:00
if coros:
try:
2020-08-25 18:02:18 +08:00
logger.debug("Running PreProcessors...")
2020-07-25 12:28:30 +08:00
await asyncio.gather(*coros)
except IgnoredException:
2020-12-09 17:51:24 +08:00
logger.opt(colors=True).info(
f"Event {event.get_event_name()} is <b>ignored</b>")
2020-07-25 12:28:30 +08:00
return
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running EventPreProcessors. "
"Event ignored!</bg #f8bbd0></r>")
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
2020-11-16 11:25:42 +08:00
if show_log:
logger.debug(f"Checking for matchers in priority {priority}...")
2020-11-16 12:35:04 +08:00
run_matchers = await _check_matcher(priority, bot, event, state)
2020-11-16 11:25:42 +08:00
pending_tasks = [
_run_matcher(matcher, bot, event, state.copy())
2020-11-16 11:25:42 +08:00
for matcher in run_matchers
]
results = await asyncio.gather(*pending_tasks, return_exceptions=True)
2020-11-16 11:25:42 +08:00
for result in results:
if isinstance(result, StopPropagation):
2020-11-16 11:25:42 +08:00
if not break_flag:
break_flag = True
logger.debug("Stop event propagation")
coros = list(map(lambda x: x(bot, event, state), _event_postprocessors))
if coros:
try:
logger.debug("Running PostProcessors...")
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running EventPostProcessors</bg #f8bbd0></r>"
)