nonebot2/nonebot/message.py

70 lines
2.0 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
2020-07-25 12:28:30 +08:00
from nonebot.exception import IgnoredException
2020-08-10 13:06:02 +08:00
from nonebot.typing import Bot, Set, Event, PreProcessor
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
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
_, _ = TrieRule.get_value(bot, event, state)
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-08-17 16:09:41 +08:00
if not await Matcher.check_perm(
bot, event) or not await Matcher.check_rule(
bot, event, state):
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:
2020-08-17 16:09:41 +08:00
await matcher.run(bot, event, state)
2020-07-04 22:51:10 +08:00
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