Skip to content

Commit

Permalink
✨ version 0.4.1
Browse files Browse the repository at this point in the history
app.on
  • Loading branch information
RF-Tar-Railt committed May 20, 2024
1 parent 2e70d6a commit fcb1392
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 40 deletions.
25 changes: 19 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,33 @@

## 示例

复读:

```python
from arclet.entari import ContextSession, Entari, WS

app = Entari(WS(host="127.0.0.1", port=5140, path="satori"))


@app.on_message()
async def repeat(session: ContextSession):
await session.send(session.content)

app.run()
```

指令 `add {a} {b}`:
```python
from arclet.entari import ContextSession, Entari, EntariCommands, WebsocketsInfo
from arclet.entari import ContextSession, Entari, EntariCommands, WS

command = EntariCommands()


@command.on("add {a} {b}")
async def add(a: int, b: int, session: ContextSession):
await session.send(f"{a + b =}")
await session.send(f"{a + b = }")


app = Entari()
app.apply(WebsocketsInfo(port=5500, token="XXX"))

app = Entari(WS(port=5500, token="XXX"))
app.run()

```
3 changes: 3 additions & 0 deletions arclet/entari/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,6 @@
from .plugin import load_plugin as load_plugin
from .plugin import load_plugins as load_plugins
from .session import ContextSession as ContextSession

WS = WebsocketsInfo
WH = WebhookInfo
15 changes: 7 additions & 8 deletions arclet/entari/command/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ class Match(Generic[T]):
"""
匹配项,表示参数是否存在于 `all_matched_args` 内
result (T): 匹配结果
available (bool): 匹配状态
Attributes:
result (T): 匹配结果
available (bool): 匹配状态
"""

result: T
Expand All @@ -25,11 +25,10 @@ class Query(Generic[T]):
"""
查询项,表示参数是否可由 `Arparma.query` 查询并获得结果
result (T): 查询结果
available (bool): 查询状态
path (str): 查询路径
Attributes:
result (T): 查询结果
available (bool): 查询状态
path (str): 查询路径
"""

result: T
Expand Down
23 changes: 21 additions & 2 deletions arclet/entari/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
import asyncio
from contextlib import suppress

from arclet.letoderea import Contexts, EventSystem, Provider, global_providers
from arclet.letoderea import BaseAuxiliary, Contexts, EventSystem, Provider, ProviderFactory, global_providers
from loguru import logger
from satori.client import App
from satori.client.account import Account
from satori.client.session import Session
from satori.config import Config
from satori.model import Event

from .event import event_parse
from .event import MessageEvent, event_parse
from .plugin import dispatchers
from .session import ContextSession

Expand Down Expand Up @@ -41,6 +41,25 @@ def __init__(self, *configs: Config):
self._ref_tasks = set()
# self.lifecycle(self.handle_lifecycle)

def on(
self,
*events: type,
priority: int = 16,
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
return self.event_system.on(*events, priority=priority, auxiliaries=auxiliaries, providers=providers)

def on_message(
self,
priority: int = 16,
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
return self.event_system.on(
MessageEvent, priority=priority, auxiliaries=auxiliaries, providers=providers
)

async def handle_event(self, account: Account, event: Event):
async def event_parse_task(connection: Account, raw: Event):
loop = asyncio.get_running_loop()
Expand Down
36 changes: 18 additions & 18 deletions arclet/entari/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def __getitem__(self, args: type[TE1]) -> MessageChain[TE1]:
Args:
args: 消息段类型
Return:
Returns:
所有类型为 `args` 的消息段
"""

Expand All @@ -115,7 +115,7 @@ def __getitem__(self, args: tuple[type[TE1], int]) -> TE1:
Args:
args: 消息段类型和索引
Return:
Returns:
类型为 `args[0]` 的消息段第 `args[1]` 个
"""

Expand All @@ -126,7 +126,7 @@ def __getitem__(self, args: tuple[type[TE1], slice]) -> MessageChain[TE1]:
Args:
args: 消息段类型和切片
Return:
Returns:
类型为 `args[0]` 的消息段切片 `args[1]`
"""

Expand All @@ -137,7 +137,7 @@ def __getitem__(self, args: int) -> TE:
Args:
args: 索引
Return:
Returns:
第 `args` 个消息段
"""

Expand All @@ -148,7 +148,7 @@ def __getitem__(self, args: slice) -> Self:
Args:
args: 切片
Return:
Returns:
消息切片 `args`
"""

Expand All @@ -160,23 +160,23 @@ def __getitem__(
if isinstance(arg1, int) and arg2 is None:
return super().__getitem__(arg1)
if isinstance(arg1, slice) and arg2 is None:
return MessageChain(super().__getitem__(arg1))
return MessageChain(super().__getitem__(arg1)) # type: ignore
if TYPE_CHECKING:
assert not isinstance(arg1, (slice, int))
if issubclass(arg1, Element) and arg2 is None:
return MessageChain(seg for seg in self if isinstance(seg, arg1))
return MessageChain(seg for seg in self if isinstance(seg, arg1)) # type: ignore
if issubclass(arg1, Element) and isinstance(arg2, int):
return [seg for seg in self if isinstance(seg, arg1)][arg2]
if issubclass(arg1, Element) and isinstance(arg2, slice):
return MessageChain([seg for seg in self if isinstance(seg, arg1)][arg2])
return MessageChain([seg for seg in self if isinstance(seg, arg1)][arg2]) # type: ignore
raise ValueError("Incorrect arguments to slice") # pragma: no cover

def __contains__(self, value: str | Element | type[Element]) -> bool:
"""检查消息段是否存在
Args:
value: 消息段或消息段类型
Return:
Returns:
消息内是否存在给定消息段或给定类型的消息段
"""
if isinstance(value, type):
Expand All @@ -195,7 +195,7 @@ def index(self, value: str | Element | type[Element], *args: SupportsIndex) -> i
value: 消息段或者消息段类型
args: start 与 end
Return:
Returns:
索引 index
Raise:
Expand All @@ -217,7 +217,7 @@ def get(self, type_: type[TE], count: int | None = None) -> MessageChain[TE]:
type_: 消息段类型
count: 获取个数
Return:
Returns:
构建的新消息
"""
if count is None:
Expand All @@ -229,15 +229,15 @@ def get(self, type_: type[TE], count: int | None = None) -> MessageChain[TE]:
if seg is None:
break
filtered.append(seg)
return filtered
return filtered # type: ignore

def count(self, value: type[Element] | str | Element) -> int:
"""计算指定消息段的个数
Args:
value: 消息段或消息段类型
Return:
Returns:
个数
"""
if isinstance(value, str):
Expand All @@ -254,7 +254,7 @@ def only(self, value: type[Element] | str | Element) -> bool:
Args:
value: 指定消息段或消息段类型
Return:
Returns:
是否仅包含指定消息段
"""
if isinstance(value, type):
Expand All @@ -269,7 +269,7 @@ def join(self, iterable: Iterable[TE1 | MessageChain[TE1]]) -> MessageChain[TE |
Args:
iterable: 要连接的消息
Return:
Returns:
连接后的消息
"""
ret = MessageChain()
Expand All @@ -280,7 +280,7 @@ def join(self, iterable: Iterable[TE1 | MessageChain[TE1]]) -> MessageChain[TE |
ret.append(msg)
else:
ret.extend(msg.copy())
return ret
return ret # type: ignore

def copy(self) -> MessageChain[TE]:
"""深拷贝消息"""
Expand All @@ -292,7 +292,7 @@ def include(self, *types: type[Element]) -> MessageChain:
Args:
types: 包含的消息段类型
Return:
Returns:
新构造的消息
"""
return MessageChain(seg for seg in self if seg.__class__ in types)
Expand All @@ -303,7 +303,7 @@ def exclude(self, *types: type[Element]) -> MessageChain:
Args:
types: 不包含的消息段类型
Return:
Returns:
新构造的消息
"""
return MessageChain(seg for seg in self if seg.__class__ not in types)
Expand Down
10 changes: 6 additions & 4 deletions arclet/entari/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ async def prompt(
) -> MessageChain:
"""发送提示消息, 并等待回复
参数:
Args:
message: 要发送的消息
timeout: 等待超时时间
timeout_message: 超时后发送的消息
"""
if self.context.type != EventType.MESSAGE_CREATED:
raise RuntimeError("Event cannot be prompted!")
Expand Down Expand Up @@ -104,7 +106,7 @@ async def send_message(
) -> list[MessageObject]:
"""发送消息
参数:
Args:
message: 要发送的消息
"""
if not self.context.channel:
Expand All @@ -117,7 +119,7 @@ async def send_private_message(
) -> list[MessageObject]:
"""发送私聊消息
参数:
Args:
message: 要发送的消息
"""
if not self.context.user:
Expand All @@ -130,7 +132,7 @@ async def update_message(
):
"""更新消息
参数:
Args:
message: 要更新的消息
"""
if not self.context.channel:
Expand Down
5 changes: 5 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,9 @@ async def echoimg(img: Image, session: ContextSession):

app = Entari(WebsocketsInfo(host="127.0.0.1", port=5140, path="satori"))


@app.on_message()
async def repeat(session: ContextSession):
await session.send(session.content)

app.run()
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "arclet-entari"
version = "0.4.0"
version = "0.4.1"
description = "Simple IM Framework based on satori-python"
authors = [
{name = "RF-Tar-Railt",email = "[email protected]"},
Expand Down Expand Up @@ -60,7 +60,7 @@ include = ["arclet/**.py"]

[tool.ruff.lint]
select = ["E", "W", "F", "UP", "C", "T", "PYI", "PT", "Q"]
ignore = ["C901", "T201", "E731", "E402"]
ignore = ["C901", "T201", "E731", "E402", "PYI055"]

[tool.pyright]
pythonVersion = "3.9"
Expand Down

0 comments on commit fcb1392

Please sign in to comment.