Skip to content

Commit

Permalink
chore: sync version
Browse files Browse the repository at this point in the history
  • Loading branch information
HsiangNianian committed Nov 14, 2023
1 parent f487802 commit ce1700a
Show file tree
Hide file tree
Showing 27 changed files with 753 additions and 619 deletions.
10 changes: 9 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,12 @@ iamai/adapter/cqhttp/

# pdm
dist/**/*
.pdm-build/**/*
.pdm-build/**/*\


# adapters
iamai/adapter/**


# tests
tests/logs
Original file line number Diff line number Diff line change
@@ -1,39 +1,44 @@
"""APScheduler 适配器。
本适配器用于实现定时任务,适配器将使用 APScheduler 实现定时任务,在设定的时间产生一个事件供插件处理。
APScheduler 使用方法请参考: [APScheduler](https://apscheduler.readthedocs.io/)
APScheduler 使用方法请参考[APScheduler](https://apscheduler.readthedocs.io/)。
"""
import asyncio
import inspect
from functools import wraps
from typing import Any, Dict, Type
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Type, Union

from apscheduler.job import Job
from apscheduler.schedulers.asyncio import AsyncIOScheduler

from iamai.plugin import Plugin
from iamai.adapter import Adapter
from iamai.log import logger, error_or_exception
from iamai.log import logger
from iamai.plugin import Plugin
from iamai.typing import PluginT

from .config import Config
from .event import APSchedulerEvent

if TYPE_CHECKING:
from apscheduler.triggers.base import BaseTrigger

__all__ = ["APSchedulerAdapter", "scheduler_decorator"]


class APSchedulerAdapter(Adapter[APSchedulerEvent, Config]):
"""APScheduler 适配器。"""

name: str = "apscheduler"
Config = Config

scheduler: AsyncIOScheduler
plugin_class_to_job: Dict[Type[Plugin], Job]
plugin_class_to_job: Dict[Type[Plugin[Any, Any, Any]], Job]

async def startup(self):
"""创建 AsyncIOScheduler 对象。"""
async def startup(self) -> None:
"""创建 `AsyncIOScheduler` 对象。"""
self.scheduler = AsyncIOScheduler(self.config.scheduler_config)
self.plugin_class_to_job = {}

async def run(self):
async def run(self) -> None:
"""启动调度器。"""
for plugin in self.bot.plugins:
if not hasattr(plugin, "__schedule__"):
Expand All @@ -46,8 +51,8 @@ async def run(self):
)
continue

trigger = getattr(plugin, "trigger")
trigger_args = getattr(plugin, "trigger_args")
trigger: Union[str, BaseTrigger] = getattr(plugin, "trigger") # noqa: B009
trigger_args: Dict[str, Any] = getattr(plugin, "trigger_args") # noqa: B009

if not isinstance(trigger, str) or not isinstance(trigger_args, dict):
logger.error(
Expand All @@ -60,77 +65,74 @@ async def run(self):
self.create_event, args=(plugin,), trigger=trigger, **trigger_args
)
except Exception as e:
error_or_exception(
self.bot.error_or_exception(
f"Plugin {plugin.__name__} add_job filed, "
"please check trigger and trigger_args:",
e,
self.bot.config.bot.log.verbose_exception,
)
else:
logger.info(f"Plugin {plugin.__name__} has been scheduled to run")

self.scheduler.start()

async def shutdown(self):
async def shutdown(self) -> None:
"""关闭调度器。"""
if self.scheduler is not None:
self.scheduler.shutdown()
self.scheduler.shutdown()

async def create_event(self, plugin_class: Type[Plugin]):
"""创建 APSchedulerEvent 事件。
async def create_event(self, plugin_class: Type[Plugin[Any, Any, Any]]) -> None:
"""创建 `APSchedulerEvent` 事件。
Args:
plugin_class: Plugin 类。
plugin_class: `Plugin` 类。
"""
logger.info(f"APSchedulerEvent set by {plugin_class} is created as scheduled")
asyncio.create_task(
self.bot.handle_event(
APSchedulerEvent(adapter=self, plugin_class=plugin_class),
handle_get=False,
show_log=False,
)
await self.handle_event(
APSchedulerEvent(adapter=self, plugin_class=plugin_class),
handle_get=False,
show_log=False,
)

async def send(self, *args, **kwargs):
async def send(self, *args: Any, **kwargs: Any) -> Any:
"""APScheduler 适配器不适用发送消息。"""
raise NotImplementedError


def scheduler_decorator(
trigger: str, trigger_args: Dict[str, Any], override_rule: bool = False
):
) -> Callable[[Type[PluginT]], Type[PluginT]]:
"""用于为插件类添加计划任务功能的装饰器。
Args:
trigger: APScheduler 触发器。
trigger_args: APScheduler 触发器参数。
override_rule: 是否重写 rule() 方法,若为 True,则会在 rule() 方法中添加处理本插件定义的计划任务事件的逻辑。
override_rule: 是否重写 `rule()` 方法。
若为 `True`,则会在 `rule()` 方法中添加处理本插件定义的计划任务事件的逻辑。
"""

def _decorator(cls: Type):
def _decorator(cls: Type[PluginT]) -> Type[PluginT]:
if not inspect.isclass(cls):
raise TypeError("can only decorate class")
if not issubclass(cls, Plugin):
raise TypeError("can only decorate Plugin class")
setattr(cls, "__schedule__", True)
setattr(cls, "trigger", trigger)
setattr(cls, "trigger_args", trigger_args)
setattr(cls, "__schedule__", True) # noqa: B010
setattr(cls, "trigger", trigger) # noqa: B010
setattr(cls, "trigger_args", trigger_args) # noqa: B010
if override_rule:

def _rule_decorator(func):
def _rule_decorator(func: Callable[[PluginT], Awaitable[bool]]) -> Any:
@wraps(func)
async def _wrapper(self, *args, **kwargs):
async def _wrapper(self: PluginT) -> bool:
if (
self.event.type == "apscheduler"
and type(self) == self.event.plugin_class
# pylint: disable-next=unidiomatic-typecheck
and type(self) is self.event.plugin_class
):
return True
else:
return await func(self, *args, **kwargs)
return await func(self)

return _wrapper

handle_func = getattr(cls, "rule")
setattr(cls, "rule", _rule_decorator(handle_func))
return cls
cls.rule = _rule_decorator(cls.rule) # type: ignore
return cls # type: ignore

return _decorator
return _decorator
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""APScheduler 适配器配置。"""
from typing import Any, Dict

from pydantic import Field

from iamai.config import ConfigModel

__all__ = ["Config"]


class Config(ConfigModel):
"""APScheduler 配置类,将在适配器被加载时被混入到机器人主配置中。
Expand All @@ -12,4 +16,4 @@ class Config(ConfigModel):
"""

__config_name__ = "apscheduler"
scheduler_config: Dict[str, Any] = {}
scheduler_config: Dict[str, Any] = Field(default_factory=dict)
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
"""APScheduler 适配器事件。"""
from typing import TYPE_CHECKING, Any, Dict, Type
from typing import TYPE_CHECKING, Any, Dict, Optional, Type, Union

from apscheduler.job import Job
from apscheduler.triggers.base import BaseTrigger

from iamai.event import Event
from iamai.plugin import Plugin

if TYPE_CHECKING:
from apscheduler.job import Job
from . import APSchedulerAdapter


from . import APSchedulerAdapter # noqa
__all__ = ["APSchedulerEvent"]


class APSchedulerEvent(Event["APSchedulerAdapter"]):
"""APSchedulerEvent 事件基类。"""

type = "apscheduler"
plugin_class: Type[Plugin]
type: Optional[str] = "apscheduler"
plugin_class: Type[Plugin] # type: ignore

@property
def job(self) -> "Job":
"""产生当前事件的 APScheduler Job 对象。"""
return self.adapter.plugin_class_to_job.get(self.plugin_class)
def job(self) -> Job:
"""产生当前事件的 APScheduler `Job` 对象。"""
return self.adapter.plugin_class_to_job[self.plugin_class]

@property
def trigger(self) -> str:
"""当前事件对应的 Plugin 的 trigger。"""
return getattr(self.plugin_class, "trigger", None)
def trigger(self) -> Union[str, BaseTrigger]:
"""当前事件对应的 Plugin 的 `trigger`。"""
return getattr(self.plugin_class, "trigger") # noqa: B009

@property
def trigger_args(self) -> Dict[str, Any]:
"""当前事件对应的 Plugin 的 trigger_args。"""
return getattr(self.plugin_class, "trigger_args", None)
"""当前事件对应的 Plugin 的 `trigger_args`。"""
return getattr(self.plugin_class, "trigger_args") # noqa: B009
2 changes: 1 addition & 1 deletion packages/iamai-adapter-apscheduler/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "iamai-adapter-apscheduler"
version = "3.2.6"
version = "3.2.7"
description = "apscheduler adapter for iamai."
authors = [{ name = "简律纯", email = "i@jyunko.cn" }]
license = { text = "MIT" }
Expand Down
2 changes: 1 addition & 1 deletion packages/iamai-adapter-bililive/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "iamai-adapter-bililive"
version = "3.2.6"
version = "3.2.7"
description = "bililive adapter for iamai."
authors = [{ name = "简律纯", email = "i@jyunko.cn" }]
license = { text = "MIT" }
Expand Down
2 changes: 1 addition & 1 deletion packages/iamai-adapter-console/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "iamai-adapter-console"
version = "3.2.6"
version = "3.2.7"
description = "Console adapter for iamai."
authors = [{ name = "简律纯", email = "i@jyunko.cn" }]
license = { text = "MIT" }
Expand Down
Loading

0 comments on commit ce1700a

Please sign in to comment.