1
0
forked from bot/app

🐛 修复一些细节小问题

This commit is contained in:
2024-10-14 00:57:33 +08:00
parent c2cb416b4e
commit 4a5dd1f727
16 changed files with 1241 additions and 1094 deletions

View File

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:44
@Author : snowykami
@Email : snowykami@outlook.com
@File : __init__.py.py
@Software: PyCharm
"""

87
liteyuki/session/event.py Normal file
View File

@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:47
@Author : snowykami
@Email : snowykami@outlook.com
@File : event.py
@Software: PyCharm
"""
from typing import Any, Optional
from liteyuki import Channel
class MessageEvent:
def __init__(
self,
bot_id: str,
message: list[dict[str, Any]] | str,
message_type: str,
raw_message: str,
session_id: str,
user_id: str,
session_type: str,
receive_channel: Optional[Channel["MessageEvent"]] = None,
data: Optional[dict[str, Any]] = None,
):
"""
轻雪抽象消息事件
Args:
bot_id: 机器人ID
message: 消息,消息段数组[{type: str, data: dict[str, Any]}]
raw_message: 原始消息(通常为纯文本的格式)
message_type: 消息类型(private, group, other)
session_id: 会话ID(私聊通常为用户ID群聊通常为群ID)
session_type: 会话类型(private, group)
receive_channel: 接收频道(用于回复消息)
data: 附加数据
"""
if data is None:
data = {}
self.message_type = message_type
self.data = data
self.bot_id = bot_id
self.message = message
self.raw_message = raw_message
self.session_id = session_id
self.session_type = session_type
self.user_id = user_id
self.receive_channel = receive_channel
def __str__(self):
return (f"Event(message_type={self.message_type}, data={self.data}, bot_id={self.bot_id}, "
f"session_id={self.session_id}, session_type={self.session_type})")
def reply(self, message: str | dict[str, Any]):
"""
回复消息
Args:
message:
Returns:
"""
reply_event = MessageEvent(
message_type=self.session_type,
message=message,
raw_message="",
data={
"message": message
},
bot_id=self.bot_id,
session_id=self.session_id,
user_id=self.user_id,
session_type=self.session_type,
receive_channel=None
)
# shared_memory.publish(self.receive_channel, reply_event)
if self.receive_channel:
self.receive_channel.send(reply_event)

View File

@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:51
@Author : snowykami
@Email : snowykami@outlook.com
@File : matcher.py
@Software: PyCharm
"""
import traceback
from typing import Any, TypeAlias, Callable, Coroutine
from liteyuki.session.event import MessageEvent
from liteyuki.session.rule import Rule
EventHandler: TypeAlias = Callable[[MessageEvent], Coroutine[None, None, Any]]
class Matcher:
def __init__(self, rule: Rule, priority: int, block: bool):
"""
匹配器
Args:
rule: 规则
priority: 优先级 >= 0
block: 是否阻断后续优先级更低的匹配器
"""
self.rule = rule
self.priority = priority
self.block = block
self.handlers: list[EventHandler] = []
def __str__(self):
return f"Matcher(rule={self.rule}, priority={self.priority}, block={self.block})"
def handle(self) -> Callable[[EventHandler], EventHandler]:
"""
添加处理函数,装饰器
Returns:
装饰器 handler
"""
def decorator(handler: EventHandler) -> EventHandler:
self.handlers.append(handler)
return handler
return decorator
async def run(self, event: MessageEvent) -> None:
"""
运行处理函数
Args:
event:
Returns:
"""
if not await self.rule(event):
return
for handler in self.handlers:
try:
await handler(event)
except Exception:
traceback.print_exc()

62
liteyuki/session/on.py Normal file
View File

@ -0,0 +1,62 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:52
@Author : snowykami
@Email : snowykami@outlook.com
@File : on.py
@Software: PyCharm
"""
from queue import Queue
from liteyuki.comm.storage import shared_memory
from liteyuki.log import logger
from liteyuki.session.event import MessageEvent
from liteyuki.session.matcher import Matcher
from liteyuki.session.rule import Rule, empty_rule
_matcher_list: list[Matcher] = []
_queue: Queue = Queue()
@shared_memory.on_subscriber_receive("event_to_liteyuki")
async def _(event: MessageEvent):
print("AA")
current_priority = -1
for i, matcher in enumerate(_matcher_list):
logger.info(f"Running matcher {matcher} for event: {event}")
await matcher.run(event)
# 同优先级不阻断,不同优先级阻断
if current_priority != matcher.priority:
current_priority = matcher.priority
if matcher.block:
break
else:
logger.info(f"No matcher matched for event: {event}")
print("BB")
def add_matcher(matcher: Matcher):
for i, m in enumerate(_matcher_list):
if m.priority < matcher.priority:
_matcher_list.insert(i, matcher)
break
else:
_matcher_list.append(matcher)
def on_message(rule: Rule = empty_rule, priority: int = 0, block: bool = False) -> Matcher:
matcher = Matcher(rule, priority, block)
# 按照优先级插入
add_matcher(matcher)
return matcher
def on_keywords(keywords: list[str], rule=empty_rule, priority: int = 0, block: bool = False) -> Matcher:
@Rule
async def on_keywords_rule(event: MessageEvent):
return any(keyword in event.raw_message for keyword in keywords)
return on_message(on_keywords_rule & rule, priority, block)

51
liteyuki/session/rule.py Normal file
View File

@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:55
@Author : snowykami
@Email : snowykami@outlook.com
@File : rule.py
@Software: PyCharm
"""
import inspect
from typing import Optional, TypeAlias, Callable, Coroutine
from liteyuki.session.event import MessageEvent
from liteyuki import get_config
_superusers: list[str] = get_config("liteyuki.superusers", [])
RuleHandlerFunc: TypeAlias = Callable[[MessageEvent], Coroutine[None, None, bool]]
"""规则函数签名"""
class Rule:
def __init__(self, handler: RuleHandlerFunc):
self.handler = handler
def __or__(self, other: "Rule") -> "Rule":
async def combined_handler(event: MessageEvent) -> bool:
return await self.handler(event) or await other.handler(event)
return Rule(combined_handler)
def __and__(self, other: "Rule") -> "Rule":
async def combined_handler(event: MessageEvent) -> bool:
return await self.handler(event) and await other.handler(event)
return Rule(combined_handler)
async def __call__(self, event: MessageEvent) -> bool:
if self.handler is None:
return True
return await self.handler(event)
@Rule
async def empty_rule(event: MessageEvent) -> bool:
return True
@Rule
async def is_su_rule(event: MessageEvent) -> bool:
return str(event.user_id) in _superusers

View File

@ -0,0 +1,10 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:47
@Author : snowykami
@Email : snowykami@outlook.com
@File : session.py
@Software: PyCharm
"""