Skip to content

Commit 4bf8512

Browse files
committed
✨ 新增on_keywords
1 parent a3a31a2 commit 4bf8512

File tree

12 files changed

+137
-22
lines changed

12 files changed

+137
-22
lines changed

liteyuki/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,9 @@
3333
"logger",
3434
]
3535

36-
__version__ = "6.3.8" # 测试版本号
36+
__version__ = "6.3.9" # 测试版本号
37+
# 6.3.9
38+
# 更改了on语法
3739

3840
# 6.3.8
3941
# 1. 初步添加对聊天的支持

liteyuki/comm/channel.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ class Channel(Generic[T]):
3838
有两种接收工作方式,但是只能选择一种,主动接收和被动接收,主动接收使用 `receive` 方法,被动接收使用 `on_receive` 装饰器
3939
"""
4040

41-
def __init__(self, _id: str, type_check: Optional[bool] = None):
41+
def __init__(self, _id: str = "", type_check: Optional[bool] = None):
4242
"""
4343
初始化通道
4444
Args:

liteyuki/comm/storage.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from liteyuki.comm import channel
1010
from liteyuki.comm.channel import Channel, ON_RECEIVE_FUNC, ASYNC_ON_RECEIVE_FUNC
11-
from liteyuki.utils import IS_MAIN_PROCESS, is_coroutine_callable, run_coroutine
11+
from liteyuki.utils import IS_MAIN_PROCESS, is_coroutine_callable, run_coroutine, run_coroutine_in_thread
1212

1313
if IS_MAIN_PROCESS:
1414
_locks = {}
@@ -220,10 +220,10 @@ def run_subscriber_receive_funcs(channel_: str, data: Any):
220220
"""
221221
if IS_MAIN_PROCESS:
222222
if channel_ in _on_main_subscriber_receive_funcs and _on_main_subscriber_receive_funcs[channel_]:
223-
run_coroutine(*[func(data) for func in _on_main_subscriber_receive_funcs[channel_]])
223+
run_coroutine_in_thread(*[func(data) for func in _on_main_subscriber_receive_funcs[channel_]])
224224
else:
225225
if channel_ in _on_sub_subscriber_receive_funcs and _on_sub_subscriber_receive_funcs[channel_]:
226-
run_coroutine(*[func(data) for func in _on_sub_subscriber_receive_funcs[channel_]])
226+
run_coroutine_in_thread(*[func(data) for func in _on_sub_subscriber_receive_funcs[channel_]])
227227

228228
def _start_receive_loop(self):
229229
"""

liteyuki/message/matcher.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,17 @@ def __init__(self, rule: Rule, priority: int, block: bool):
3434
def __str__(self):
3535
return f"Matcher(rule={self.rule}, priority={self.priority}, block={self.block})"
3636

37-
def handle(self, handler: EventHandler) -> EventHandler:
37+
def handle(self) -> Callable[[EventHandler], EventHandler]:
3838
"""
3939
添加处理函数,装饰器
40-
Args:
41-
handler:
4240
Returns:
43-
EventHandler
41+
装饰器 handler
4442
"""
45-
self.handlers.append(handler)
46-
return handler
43+
def decorator(handler: EventHandler) -> EventHandler:
44+
self.handlers.append(handler)
45+
return handler
46+
47+
return decorator
4748

4849
async def run(self, event: MessageEvent) -> None:
4950
"""

liteyuki/message/on.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from liteyuki.log import logger
1616
from liteyuki.message.event import MessageEvent
1717
from liteyuki.message.matcher import Matcher
18-
from liteyuki.message.rule import Rule
18+
from liteyuki.message.rule import Rule, empty_rule
1919

2020
_matcher_list: list[Matcher] = []
2121
_queue: Queue = Queue()
@@ -34,7 +34,7 @@ async def _(event: MessageEvent):
3434
break
3535

3636

37-
def on_message(rule: Rule = Rule(), priority: int = 0, block: bool = True) -> Matcher:
37+
def on_message(rule: Rule = empty_rule, priority: int = 0, block: bool = False) -> Matcher:
3838
matcher = Matcher(rule, priority, block)
3939
# 按照优先级插入
4040
for i, m in enumerate(_matcher_list):
@@ -44,3 +44,10 @@ def on_message(rule: Rule = Rule(), priority: int = 0, block: bool = True) -> Ma
4444
else:
4545
_matcher_list.append(matcher)
4646
return matcher
47+
48+
49+
def on_keywords(keywords: list[str], rule=empty_rule, priority: int = 0, block: bool = False) -> Matcher:
50+
@Rule
51+
async def on_keywords_rule(event: MessageEvent):
52+
return any(keyword in event.raw_message for keyword in keywords)
53+
return on_message(on_keywords_rule & rule, priority, block)

liteyuki/message/rule.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,26 +8,37 @@
88
@File : rule.py
99
@Software: PyCharm
1010
"""
11-
11+
import inspect
1212
from typing import Optional, TypeAlias, Callable, Coroutine
1313

1414
from liteyuki.message.event import MessageEvent
1515

16-
RuleHandler: TypeAlias = Callable[[MessageEvent], Coroutine[None, None, bool]]
16+
RuleHandlerFunc: TypeAlias = Callable[[MessageEvent], Coroutine[None, None, bool]]
1717
"""规则函数签名"""
1818

1919

2020
class Rule:
21-
def __init__(self, handler: Optional[RuleHandler] = None):
21+
def __init__(self, handler: RuleHandlerFunc):
2222
self.handler = handler
2323

2424
def __or__(self, other: "Rule") -> "Rule":
25-
return Rule(lambda event: self.handler(event) or other.handler(event))
25+
async def combined_handler(event: MessageEvent) -> bool:
26+
return await self.handler(event) or await other.handler(event)
27+
28+
return Rule(combined_handler)
2629

2730
def __and__(self, other: "Rule") -> "Rule":
28-
return Rule(lambda event: self.handler(event) and other.handler(event))
31+
async def combined_handler(event: MessageEvent) -> bool:
32+
return await self.handler(event) and await other.handler(event)
33+
34+
return Rule(combined_handler)
2935

3036
async def __call__(self, event: MessageEvent) -> bool:
3137
if self.handler is None:
3238
return True
3339
return await self.handler(event)
40+
41+
42+
@Rule
43+
async def empty_rule(event: MessageEvent) -> bool:
44+
return True

liteyuki/utils.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import asyncio
66
import inspect
77
import multiprocessing
8+
import threading
89
from pathlib import Path
910
from typing import Any, Callable, Coroutine
1011

@@ -61,6 +62,16 @@ def run_coroutine(*coro: Coroutine):
6162
# 捕获其他异常,防止协程被重复等待
6263
logger.error(f"Exception occurred: {e}")
6364

65+
def run_coroutine_in_thread(*coro: Coroutine):
66+
"""
67+
在新线程中运行协程
68+
Args:
69+
coro:
70+
71+
Returns:
72+
73+
"""
74+
threading.Thread(target=run_coroutine, args=coro, daemon=True).start()
6475

6576
def path_to_module_name(path: Path) -> str:
6677
"""
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
4+
5+
@Time : 2024/8/22 上午9:06
6+
@Author : snowykami
7+
@Email : snowykami@outlook.com
8+
@File : anti_dislink.py
9+
@Software: PyCharm
10+
"""
11+
import random
12+
from liteyuki.plugin import PluginMetadata, PluginType
13+
14+
from liteyuki.message.on import on_keywords
15+
16+
__plugin_meta__ = PluginMetadata(
17+
name="严禁断联化",
18+
type=PluginType.APPLICATION
19+
)
20+
21+
22+
@on_keywords(["看看你的", "看看j", "给我看看"]).handle()
23+
async def _(event):
24+
event.reply(random.choice(["No dislink", "严禁断联化"]))

src/liteyuki_plugins/hello_liteyuki.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@
1414

1515
__plugin_meta__ = PluginMetadata(
1616
name="你好轻雪",
17-
type=PluginType.TEST
17+
type=PluginType.APPLICATION
1818
)
1919

2020

21-
@on_message().handle
21+
@on_message().handle()
2222
async def _(event: MessageEvent):
2323
if str(event.raw_message) == "你好轻雪":
2424
event.reply("你好呀")
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
4+
5+
@Time : 2024/8/22 上午8:37
6+
@Author : snowykami
7+
@Email : snowykami@outlook.com
8+
@File : ts_chan_main.py
9+
@Software: PyCharm
10+
"""
11+
import asyncio
12+
13+
from liteyuki.comm import Channel, set_channel, get_channel
14+
from liteyuki import get_bot
15+
16+
set_channel("chan-main", Channel("chan-main"))
17+
set_channel("chan-sub", Channel("chan-sub"))
18+
19+
chan_main = get_channel("chan-main")
20+
21+
22+
# @get_bot().on_after_start
23+
# async def _():
24+
# while True:
25+
# chan_main.send("Hello, World!")
26+
# await asyncio.sleep(5)

0 commit comments

Comments
 (0)