Skip to content

Commit

Permalink
🐛 hotfix: from mypy import
Browse files Browse the repository at this point in the history
  • Loading branch information
snowykami committed Oct 19, 2024
1 parent f117da7 commit 6b64a0c
Show file tree
Hide file tree
Showing 13 changed files with 121 additions and 613 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@
### 感谢
- 所有贡献者们

### 参考
### 参考及鸣谢
- [nonebot-plugin-uninfo](https://github.com/RF-Tar-Railt/nonebot-plugin-uninfo)为会话部分用户信息提供了参考
- [nonebot-plugin-alconna](https://github.com/nonebot/plugin-alconna/)为消息部分提供了参考


[OneBot]: https://img.shields.io/badge/OneBot-11/12-blue?style=for-the-badge
Expand Down
30 changes: 11 additions & 19 deletions liteyuki/bot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import asyncio
import atexit
import os
import platform
import signal
import sys
import threading
import time
from typing import Any, Optional

from magicoca import Chan

from liteyuki.bot.lifespan import LIFESPAN_FUNC, Lifespan, PROCESS_LIFESPAN_FUNC
from liteyuki.comm.channel import get_channel
from liteyuki.core.manager import ProcessManager
# new version
from liteyuki.core.manager import sub_process_manager
from liteyuki.log import init_log, logger
from liteyuki.plugin import load_plugin
from liteyuki.session import message_handler_thread
from liteyuki.utils import IS_MAIN_PROCESS

# new version
from liteyuki.core.manager import sub_process_manager

__all__ = [
"LiteyukiBot",
"get_bot",
Expand All @@ -33,6 +33,10 @@ def __init__(self, **kwargs) -> None:
Args:
**kwargs: 配置
"""
"""总通道"""
self.i_chan = Chan[Any]() # 外部输入通道
self.o_chan = Chan[Any]() # 外部输出通道

"""常规操作"""
print_logo()
global _BOT_INSTANCE
Expand Down Expand Up @@ -65,7 +69,7 @@ async def _run(self):
await self.lifespan.before_start() # 启动前钩子
sub_process_manager.start_all()
await self.lifespan.after_start() # 启动后钩子
await self.keep_alive()
message_handler_thread([_.ctx.sub_chan for _ in sub_process_manager.processes.values()])

def run(self):
"""
Expand All @@ -77,19 +81,7 @@ def run(self):
except KeyboardInterrupt:
logger.opt(colors=True).info("<y>Liteyuki is stopping...</y>")
self.stop()
logger.opt(colors=True).info("<y>Liteyuki is stopped...</y>")

async def keep_alive(self):
"""
保持轻雪运行
"""
logger.info("Liteyuki is keeping alive...")
try:
while not self.stop_event.is_set():
await asyncio.sleep(0.1)
except Exception:
logger.info("Liteyuki is exiting...")
self.stop()
logger.opt(colors=True).info("<y>Liteyuki is stopped !</y>")

def restart(self, delay: int = 0):
"""
Expand Down
Empty file added liteyuki/bot/iobus.py
Empty file.
39 changes: 32 additions & 7 deletions liteyuki/core/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,17 +225,14 @@ def is_process_alive(self, name: str) -> bool:


class _SubProcessManager:
"""
子进程管理器
若要子进程间通信,请先在子进程A中发送通信事件给主进程,包含当前进程信息及上下文信息,主进程再将信息发送给子进程B,子进程B再根据信息进行操作
"""

def __init__(self):
self.processes: dict[str, SubProcess] = {}

def new_process(
self, name: str, *args, **kwargs
) -> Callable[[ProcessFuncType], None]:
def decorator(func: ProcessFuncType):
self.processes[name] = SubProcess(name, func, *args, **kwargs)

return decorator

def add(self, name: str, func: ProcessFuncType, *args, **kwargs):
"""
Expand Down Expand Up @@ -268,5 +265,33 @@ def start_all(self):
process.start()
logger.debug(f"Starting process {name}")

def terminate(self, name: str):
"""
终止指定子进程
Args:
name: 子进程名称
Returns:
"""
if name not in self.processes:
raise KeyError(f"Process {name} not found.")
self.processes[name].terminate()

def terminate_all(self):
"""
终止所有子进程
"""
for name, process in self.processes.items():
process.terminate()
logger.debug(f"Terminating process {name}")

def get_process(self, name: str) -> SubProcess | None:
"""
获取指定子进程
Args:
name: 子进程名称
Returns:
"""
return self.processes.get(name, None)


sub_process_manager = _SubProcessManager()
23 changes: 16 additions & 7 deletions liteyuki/session/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
# -*- coding: utf-8 -*-
"""
Copyright (C) 2020-2024 LiteyukiStudio. All Rights Reserved
@Time : 2024/8/19 下午10:44
@Author : snowykami
@Email : [email protected]
@File : __init__.py.py
@Software: PyCharm
该模块参考并引用了nonebot-plugin-alconna的消息段定义
"""
from typing import Any

from magicoca import Chan, select
from mypy.server.objgraph import Iterable
from six import Iterator


def message_handler_thread(i_chans: Iterable[Chan[Any]]):
"""
Args:
i_chans: 多路输入管道组
Returns:
"""
for msg in select(*i_chans):
print("Recv from anybot", msg)
Empty file.
51 changes: 51 additions & 0 deletions liteyuki/session/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from pydantic import BaseModel

class User(BaseModel):
"""
用户信息
Attributes:
id: 用户ID
name: 用户名
nick: 用户昵称
avatar: 用户头像图链接
"""
id: str
name: str | None
nick: str | None
avatar: str | None

class Scene(BaseModel):
"""
场景信息
Attributes:
id: 场景ID
type: 场景类型
name: 场景名
avatar: 场景头像图链接
parent: 父场景
"""
id: str
type: str
name: str | None
avatar: str | None
parent: "Scene | None"

class Session(BaseModel):
"""
会话信息
Attributes:
self_id: 机器人ID
adapter: 适配器ID
scope: 会话范围
scene: 场景信息
user: 用户信息
member: 成员信息,仅频道及群聊有效
operator: 操作者信息,仅频道及群聊有效
"""
self_id: str
adapter: str
scope: str
scene: Scene
user: User
member: "Member | None"
operator: "Member | None"
20 changes: 0 additions & 20 deletions liteyuki/session/on.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,13 @@

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:
Expand Down
10 changes: 0 additions & 10 deletions liteyuki/session/session.py

This file was deleted.

Loading

0 comments on commit 6b64a0c

Please sign in to comment.