nonebot2/nonebot/message.py

65 lines
1.8 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
from nonebot.event import Event
from nonebot.matcher import matchers
2020-08-07 17:05:08 +08:00
from nonebot.typing import Set, Callable
2020-07-25 12:28:30 +08:00
from nonebot.exception import IgnoredException
_event_preprocessors: Set[Callable] = set()
def event_preprocessor(func: Callable) -> Callable:
_event_preprocessors.add(func)
return func
2020-07-04 22:51:10 +08:00
2020-07-11 17:32:03 +08:00
async def handle_event(bot, event: Event):
2020-07-04 22:51:10 +08:00
# TODO: PreProcess
2020-07-25 12:28:30 +08:00
coros = []
for preprocessor in _event_preprocessors:
coros.append(preprocessor(bot, event))
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
for priority in sorted(matchers.keys()):
2020-08-06 17:54:55 +08:00
index = 0
while index <= len(matchers[priority]):
2020-07-04 22:51:10 +08:00
Matcher = matchers[priority][index]
2020-08-06 17:54:55 +08:00
# Delete expired Matcher
if datetime.now() > Matcher.expire_time:
del matchers[priority][index]
continue
# Check rule
2020-07-11 17:32:03 +08:00
try:
2020-07-25 12:28:30 +08:00
if not Matcher.check_rule(bot, event):
2020-08-06 17:54:55 +08:00
index += 1
2020-07-11 17:32:03 +08:00
continue
except Exception as e:
logger.error(
f"Rule check failed for matcher {Matcher}. Ignored.")
logger.exception(e)
2020-07-04 22:51:10 +08:00
continue
matcher = Matcher()
2020-08-06 17:54:55 +08:00
# TODO: BeforeMatcherRun
2020-07-04 22:51:10 +08:00
if Matcher.temp:
del matchers[priority][index]
try:
await matcher.run(bot, event)
except Exception as e:
2020-07-11 17:32:03 +08:00
logger.error(f"Running matcher {matcher} failed.")
2020-07-04 22:51:10 +08:00
logger.exception(e)
return