Skip to content

Commit

Permalink
✨ shortcut listen
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Dec 26, 2024
1 parent df92355 commit 38314be
Show file tree
Hide file tree
Showing 8 changed files with 42 additions and 46 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ app.run()
指令 `add {a} {b}`:

```python
from arclet.entari import Session, Entari, WS, command
from arclet.entari import Entari, WS, command

@command.on("add {a} {b}")
def add(a: int, b: int):
Expand All @@ -87,7 +87,7 @@ app.run()
编写插件:

```python
from arclet.entari import Session, MessageCreatedEvent, metadata, plugin
from arclet.entari import Session, MessageCreatedEvent, metadata, listen

metadata(
name="Hello, World!",
Expand All @@ -97,7 +97,7 @@ metadata(
)
# or __plugin_metadata__ = PluginMetadata(...)

@plugin.dispatch(MessageCreatedEvent)
@listen(MessageCreatedEvent) # or plugin.dispatch(MessageCreatedEvent)
async def _(session: Session):
await session.send("Hello, World!")
```
Expand Down
5 changes: 4 additions & 1 deletion arclet/entari/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from arclet.letoderea import bind as bind
from arclet.letoderea import es as es
from satori import ArgvInteraction as ArgvInteraction
from satori import At as At
from satori import Audio as Audio
Expand Down Expand Up @@ -48,19 +49,21 @@
from .message import MessageChain as MessageChain
from .plugin import Plugin as Plugin
from .plugin import PluginMetadata as PluginMetadata
from .plugin import add_service as add_service
from .plugin import declare_static as declare_static
from .plugin import dispose as dispose_plugin # noqa: F401
from .plugin import keeping as keeping
from .plugin import load_plugin as load_plugin
from .plugin import load_plugins as load_plugins
from .plugin import metadata as metadata
from .plugin import package as package
from .plugin import plugin_config as plugin_config
from .plugin import unload_plugin as unload_plugin
from .session import Session as Session
from .utils.local_data import local_data as local_data

WS = WebsocketsInfo
WH = WebhookInfo
filter_ = Filter
listen = es.on

__version__ = "0.10.5"
16 changes: 8 additions & 8 deletions arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
except ModuleNotFoundError:
raise ImportError("Please install `watchfiles` first. Install with `pip install arclet-entari[reload]`")

from arclet.entari import Plugin, declare_static, dispose_plugin, load_plugin, metadata
from arclet.entari import add_service, declare_static, load_plugin, metadata, plugin_config, unload_plugin
from arclet.entari.config import EntariConfig
from arclet.entari.event.config import ConfigReload
from arclet.entari.logger import log
Expand Down Expand Up @@ -78,7 +78,7 @@ async def watch(self):
logger("INFO", f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
pid = plugin.id
del plugin
dispose_plugin(pid)
unload_plugin(pid)
if plugin := load_plugin(pid):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
Expand Down Expand Up @@ -127,7 +127,7 @@ async def watch_config(self):
if plugin_name not in EntariConfig.instance.plugin:
if plugin := find_plugin(pid):
del plugin
dispose_plugin(pid)
unload_plugin(pid)
logger("INFO", f"Disposed plugin <blue>{pid!r}</blue>")
continue
if old_plugin[plugin_name] != EntariConfig.instance.plugin[plugin_name]:
Expand All @@ -152,7 +152,7 @@ async def watch_config(self):
continue
logger("INFO", f"Detected <blue>{pid!r}</blue>'s config change, reloading...")
plugin_file = str(plugin.module.__file__)
dispose_plugin(plugin_name)
unload_plugin(plugin_name)
if plugin := load_plugin(plugin_name, new_conf):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
Expand Down Expand Up @@ -186,11 +186,11 @@ async def launch(self, manager: Launart):
self.fail.clear()


plug = Plugin.current()
watch_dirs = plug.config.get("watch_dirs", ["."])
watch_config = plug.config.get("watch_config", False)
conf = plugin_config()
watch_dirs = conf.get("watch_dirs", ["."])
watch_config = conf.get("watch_config", False)

plug.service(serv := Watcher(watch_dirs, watch_config))
add_service(serv := Watcher(watch_dirs, watch_config))


@es.on(ConfigReload)
Expand Down
41 changes: 14 additions & 27 deletions arclet/entari/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from contextlib import suppress
import os

from arclet.letoderea import BaseAuxiliary, Contexts, Param, Provider, ProviderFactory, Subscriber, es, global_providers
from arclet.letoderea import Contexts, Param, Provider, ProviderFactory, es, global_providers
from creart import it
from launart import Launart, Service
from satori import LoginStatus
Expand All @@ -21,7 +21,7 @@
from .event.send import SendResponse
from .logger import log
from .plugin import load_plugin, plugin_config, requires
from .plugin.model import Plugin, RootlessPlugin
from .plugin.model import RootlessPlugin
from .plugin.service import plugin_service
from .session import EntariProtocol, Session

Expand Down Expand Up @@ -54,17 +54,18 @@ async def __call__(self, context: Contexts):
return context["account"]


class PluginProvider(Provider[Plugin]):
async def __call__(self, context: Contexts):
subscriber: Subscriber = context["$subscriber"]
func = subscriber.callable_target
if hasattr(func, "__globals__") and "__plugin__" in func.__globals__: # type: ignore
return func.__globals__["__plugin__"]
if hasattr(func, "__module__"):
return plugin_service.plugins.get(func.__module__)
#
# class PluginProvider(Provider[Plugin]):
# async def __call__(self, context: Contexts):
# subscriber: Subscriber = context["$subscriber"]
# func = subscriber.callable_target
# if hasattr(func, "__globals__") and "__plugin__" in func.__globals__: # type: ignore
# return func.__globals__["__plugin__"]
# if hasattr(func, "__module__"):
# return plugin_service.plugins.get(func.__module__)


global_providers.extend([ApiProtocolProvider(), SessionProvider(), AccountProvider(), PluginProvider()])
global_providers.extend([ApiProtocolProvider(), SessionProvider(), AccountProvider()])


@RootlessPlugin.apply("record_message")
Expand Down Expand Up @@ -166,22 +167,8 @@ def reset_self(self, scope, key, value):
for conn in self.connections:
it(Launart).add_component(conn)

def on(
self,
*events: type,
priority: int = 16,
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
return es.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 es.on(MessageCreatedEvent, priority=priority, auxiliaries=auxiliaries, providers=providers)
def on_message(self, priority: int = 16):
return es.on(MessageCreatedEvent, priority=priority)

def ensure_manager(self, manager: Launart):
self.manager = manager
Expand Down
12 changes: 9 additions & 3 deletions arclet/entari/plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .model import RegisterNotInPluginError
from .model import RootlessPlugin as RootlessPlugin
from .model import StaticPluginDispatchError, _current_plugin
from .model import TE, Plugin
from .model import TE, TS, Plugin
from .model import keeping as keeping
from .module import import_plugin
from .module import package as package
Expand Down Expand Up @@ -75,7 +75,7 @@ def load_plugin(
log.plugin.opt(colors=True).debug(
f"reloading <y>{mod.__name__}</y>'s referent <y>{referent!r}</y>"
)
dispose(referent)
unload_plugin(referent)
if not load_plugin(referent):
plugin_service._referents[mod.__name__].add(referent)
else:
Expand All @@ -99,7 +99,7 @@ def load_plugins(dir_: str | PathLike | Path):
load_plugin(".".join(p.parts[:-1:1]) + "." + p.stem)


def dispose(plugin: str):
def unload_plugin(plugin: str):
while plugin in plugin_service._subplugined:
plugin = plugin_service._subplugined[plugin]
if plugin not in plugin_service.plugins:
Expand Down Expand Up @@ -132,6 +132,12 @@ def declare_static():
raise StaticPluginDispatchError("static plugin cannot dispatch events")


def add_service(serv: TS | type[TS]) -> TS:
if not (plugin := _current_plugin.get(None)):
raise LookupError("no plugin context found")
return plugin.service(serv)


def find_plugin(name: str) -> Plugin | None:
if name in plugin_service.plugins:
return plugin_service.plugins[name]
Expand Down
3 changes: 2 additions & 1 deletion arclet/entari/plugin/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

T = TypeVar("T")
TE = TypeVar("TE")
TS = TypeVar("TS", bound=Service)
R = TypeVar("R")


Expand Down Expand Up @@ -359,7 +360,7 @@ def proxy(self):
def subproxy(self, sub_id: str):
return proxy(plugin_service.plugins[sub_id].module)

def service(self, serv: Service | type[Service]):
def service(self, serv: TS | type[TS]) -> TS:
if isinstance(serv, type):
serv = serv()
self._services[serv.id] = serv
Expand Down
1 change: 0 additions & 1 deletion example_plugin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import sys
from arclet.entari import (
Session,
MessageChain,
Expand Down
4 changes: 2 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from satori import Image

from arclet.entari import Session, Entari, command, load_plugin, dispose_plugin
from arclet.entari import Session, Entari, command, load_plugin, unload_plugin


@command.on("echoimg {img}")
Expand All @@ -21,7 +21,7 @@ async def load(plugin: str, session: Session):

@command.on("unload {plugin}")
async def unload(plugin: str, session: Session):
if dispose_plugin(plugin):
if unload_plugin(plugin):
await session.send_message(f"Unloaded {plugin}")
else:
await session.send_message(f"Failed to unload {plugin}")
Expand Down

0 comments on commit 38314be

Please sign in to comment.