Skip to content

Commit

Permalink
💥 upgrade to Letoderea 0.14
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Dec 25, 2024
1 parent 187ff8f commit 9a9c9aa
Show file tree
Hide file tree
Showing 20 changed files with 335 additions and 358 deletions.
11 changes: 0 additions & 11 deletions arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,11 @@ async def watch(self):
logger("INFO", f"Plugin <y>{plugin.id!r}</y> is static, ignored.")
continue
logger("INFO", f"Detected change in <blue>{plugin.id!r}</blue>, reloading...")
await plugin._cleanup()
pid = plugin.id
del plugin
dispose_plugin(pid)
if plugin := load_plugin(pid):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
await plugin._startup()
await plugin._ready()
del plugin
else:
logger("ERROR", f"Failed to reload <blue>{pid!r}</blue>")
Expand All @@ -92,8 +89,6 @@ async def watch(self):
logger("INFO", f"Detected change in {change[1]!r} which failed to reload, retrying...")
if plugin := load_plugin(self.fail[change[1]]):
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
await plugin._startup()
await plugin._ready()
del plugin
del self.fail[change[1]]
else:
Expand Down Expand Up @@ -131,7 +126,6 @@ async def watch_config(self):
pid = plugin_name.replace("::", "arclet.entari.builtins.")
if plugin_name not in EntariConfig.instance.plugin:
if plugin := find_plugin(pid):
await plugin._cleanup()
del plugin
dispose_plugin(pid)
logger("INFO", f"Disposed plugin <blue>{pid!r}</blue>")
Expand All @@ -158,11 +152,8 @@ async def watch_config(self):
continue
logger("INFO", f"Detected <blue>{pid!r}</blue>'s config change, reloading...")
plugin_file = str(plugin.module.__file__)
await plugin._cleanup()
dispose_plugin(plugin_name)
if plugin := load_plugin(plugin_name, new_conf):
await plugin._startup()
await plugin._ready()
logger("INFO", f"Reloaded <blue>{plugin.id!r}</blue>")
del plugin
else:
Expand All @@ -177,8 +168,6 @@ async def watch_config(self):
continue
if not (plugin := load_plugin(plugin_name)):
continue
await plugin._startup()
await plugin._ready()
del plugin

async def launch(self, manager: Launart):
Expand Down
17 changes: 8 additions & 9 deletions arclet/entari/command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@
from arclet.alconna import Alconna, Arg, Args, CommandMeta, Namespace, command_manager, config
from arclet.alconna.tools.construct import AlconnaString, alconna_from_format
from arclet.alconna.typing import TAValue
from arclet.letoderea import BackendPublisher, BaseAuxiliary, Provider, Subscriber, es
from arclet.letoderea.event import get_providers
from arclet.letoderea import BaseAuxiliary, Provider, Scope, Subscriber, es
from arclet.letoderea.handler import generate_contexts
from arclet.letoderea.provider import ProviderFactory
from arclet.letoderea.provider import ProviderFactory, get_providers
from arclet.letoderea.typing import Contexts, TTarget
from nepattern import DirectPattern
from satori.element import Text
Expand All @@ -33,8 +32,8 @@ class EntariCommands:

def __init__(self, need_notice_me: bool = False, need_reply_me: bool = False, use_config_prefix: bool = True):
self.trie: CharTrie[Subscriber[Optional[Union[str, MessageChain]]]] = CharTrie()
self.publisher = BackendPublisher("entari.command")
self.publisher.bind(*get_providers(MessageCreatedEvent), AlconnaProviderFactory())
self.scope = Scope("entari.command")
self.scope.bind(*get_providers(MessageCreatedEvent), AlconnaProviderFactory())
self.judge = MessageJudges(need_notice_me, need_reply_me, use_config_prefix)
config.namespaces["Entari"] = Namespace(
self.__namespace__,
Expand Down Expand Up @@ -143,8 +142,8 @@ def wrapper(func: TTarget[Optional[TM]]) -> Subscriber[Optional[TM]]:
f" {arg.value.target}" for arg in _command.args if isinstance(arg.value, DirectPattern)
)
auxiliaries.insert(0, AlconnaSuppiler(_command))
target = self.publisher.register(func, auxiliaries=auxiliaries, providers=providers)
self.publisher.remove_subscriber(target)
target = self.scope.register(func, auxiliaries=auxiliaries, providers=providers)
self.scope.remove_subscriber(target)
self.trie[key] = target

def _remove(_):
Expand All @@ -168,8 +167,8 @@ def _remove(_):
for prefix in cast(list[str], _command.prefixes):
keys.append(prefix + _command.command)

target = self.publisher.register(func, auxiliaries=auxiliaries, providers=providers)
self.publisher.remove_subscriber(target)
target = self.scope.register(func, auxiliaries=auxiliaries, providers=providers)
self.scope.remove_subscriber(target)

for _key in keys:
self.trie[_key] = target
Expand Down
32 changes: 13 additions & 19 deletions arclet/entari/command/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
from typing import Any

from arclet.alconna import Alconna, command_manager
from arclet.letoderea import BaseAuxiliary, Provider, ProviderFactory
from arclet.letoderea import BaseAuxiliary, Provider, ProviderFactory, es

from ..event import MessageCreatedEvent
from ..event.command import pub as execute_handles
from ..event.command import CommandExecute
from ..plugin.model import Plugin, PluginDispatcher
from .model import Match, Query
from .provider import AlconnaProviderFactory, AlconnaSuppiler, Assign, MessageJudges, _seminal

execute_handles.bind(AlconnaProviderFactory())
exec_pub = es.define(CommandExecute)


class AlconnaPluginDispatcher(PluginDispatcher):
Expand All @@ -25,10 +25,12 @@ def __init__(
use_config_prefix: bool = True,
):
self.supplier = AlconnaSuppiler(command)
super().__init__(plugin, MessageCreatedEvent)

self.publisher.bind(MessageJudges(need_reply_me, need_notice_me, use_config_prefix), self.supplier)
self.publisher.bind(AlconnaProviderFactory())
super().__init__(plugin, MessageCreatedEvent, command.path)
self.scope.bind(
MessageJudges(need_reply_me, need_notice_me, use_config_prefix),
self.supplier,
AlconnaProviderFactory(),
)

def assign(
self,
Expand All @@ -55,15 +57,7 @@ def on_execute(
auxiliaries: list[BaseAuxiliary] | None = None,
providers: list[Provider | type[Provider] | ProviderFactory | type[ProviderFactory]] | None = None,
):
_auxiliaries = auxiliaries or []
_auxiliaries.append(self.supplier)

def wrapper(func):
sub = execute_handles.register(func, priority=priority, auxiliaries=_auxiliaries, providers=providers)
self._subscribers.append(sub)
return sub

return wrapper
return self.scope.register(priority=priority, auxiliaries=auxiliaries, providers=providers, publisher=exec_pub)

Match = Match
Query = Query
Expand All @@ -78,7 +72,7 @@ def mount(
if not (plugin := Plugin.current()):
raise LookupError("no plugin context found")
disp = AlconnaPluginDispatcher(plugin, cmd, need_reply_me, need_notice_me, use_config_prefix)
if disp.publisher.id in plugin.dispatchers:
return plugin.dispatchers[disp.id] # type: ignore
plugin.dispatchers[disp.publisher.id] = disp
if disp.scope.id in plugin.dispatchers:
return plugin.dispatchers[disp.scope.id] # type: ignore
plugin.dispatchers[disp.scope.id] = disp
return disp
35 changes: 16 additions & 19 deletions arclet/entari/command/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from arclet.alconna import Alconna, Arparma, Duplication, Empty, output_manager
from arclet.alconna.builtin import generate_duplication
from arclet.letoderea import Contexts, Interface, JudgeAuxiliary, Param, Provider, Scope, Subscriber, SupplyAuxiliary
from arclet.letoderea import BaseAuxiliary, Contexts, Interface, Param, Provider, Subscriber
from arclet.letoderea.provider import ProviderFactory
from nepattern.util import CUnionType
from satori.element import Text
Expand All @@ -30,14 +30,13 @@ def _remove_config_prefix(message: MessageChain):
return MessageChain()


class MessageJudges(JudgeAuxiliary):
class MessageJudges(BaseAuxiliary):
def __init__(self, need_reply_me: bool, need_notice_me: bool, use_config_prefix: bool):
super().__init__(priority=30)
self.need_reply_me = need_reply_me
self.need_notice_me = need_notice_me
self.use_config_prefix = use_config_prefix

async def __call__(self, scope: Scope, interface: Interface):
async def on_prepare(self, interface: Interface):
if "$message_content" in interface.ctx:
message: MessageChain = interface.ctx["$message_content"]
is_reply_me = interface.ctx.get("is_reply_me", False)
Expand All @@ -52,22 +51,25 @@ async def __call__(self, scope: Scope, interface: Interface):
return (await interface.query(MessageChain, "message", force_return=True)) is not None

@property
def scopes(self) -> set[Scope]:
return {Scope.prepare}
def before(self) -> set[str]:
return {"entari.filter"}

@property
def after(self) -> set[str]:
return {"entari.command/supplier"}

@property
def id(self) -> str:
return "entari.command/message_judges"


class AlconnaSuppiler(SupplyAuxiliary):
class AlconnaSuppiler(BaseAuxiliary):
cmd: Alconna

def __init__(self, cmd: Alconna):
super().__init__(priority=40)
self.cmd = cmd

async def __call__(self, scope: Scope, interface: Interface) -> Optional[Union[bool, Interface.Update]]:
async def on_prepare(self, interface: Interface) -> Optional[Union[bool, Interface.Update]]:
message = await interface.query(MessageChain, "message", force_return=True)
if not message:
return False
Expand All @@ -88,10 +90,6 @@ async def __call__(self, scope: Scope, interface: Interface) -> Optional[Union[b
return interface.update(alc_result=CommandResult(self.cmd, _res, may_help_text))
return False

@property
def scopes(self) -> set[Scope]:
return {Scope.prepare}

@property
def id(self) -> str:
return "entari.command/supplier"
Expand Down Expand Up @@ -136,14 +134,13 @@ async def __call__(self, context: Contexts):
_seminal = type("_seminal", (object,), {})


class Assign(JudgeAuxiliary):
class Assign(BaseAuxiliary):
def __init__(self, path: str, value: Any = _seminal, or_not: bool = False):
super().__init__(priority=60)
self.path = path
self.value = value
self.or_not = or_not

async def __call__(self, scope: Scope, interface: Interface) -> Optional[bool]:
async def on_prepare(self, interface: Interface) -> Optional[bool]:
result = await interface.query(CommandResult, "alc_result", force_return=True)
if result is None:
return False
Expand All @@ -161,8 +158,8 @@ async def __call__(self, scope: Scope, interface: Interface) -> Optional[bool]:
return False

@property
def scopes(self) -> set[Scope]:
return {Scope.prepare}
def before(self) -> set[str]:
return {"entari.command/supplier"}

@property
def id(self) -> str:
Expand Down Expand Up @@ -192,4 +189,4 @@ def validate(self, param: Param):


def get_cmd(target: Subscriber):
return next(a for a in target.auxiliaries[Scope.prepare] if isinstance(a, AlconnaSuppiler)).cmd
return next(a for a in target.auxiliaries["prepare"] if isinstance(a, AlconnaSuppiler)).cmd
7 changes: 2 additions & 5 deletions arclet/entari/event/command.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from dataclasses import dataclass
from typing import Union

from arclet.letoderea import Contexts, Provider, es
from arclet.letoderea import Contexts, Provider, make_event

from ..message import MessageChain


@dataclass
@make_event(name="entari.event/command_execute")
class CommandExecute:
command: Union[str, MessageChain]

Expand All @@ -20,8 +21,4 @@ class CommandProvider(Provider[MessageChain]):
async def __call__(self, context: Contexts):
return context.get("command")

__publisher__ = "entari.event/command_execute"
__result_type__: "type[str | MessageChain]" = Union[str, MessageChain]


pub = es.define(CommandExecute.__publisher__, CommandExecute)
7 changes: 2 additions & 5 deletions arclet/entari/event/config.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
from dataclasses import dataclass
from typing import Any, Optional

from arclet.letoderea import es
from arclet.letoderea import make_event


@dataclass
@make_event(name="entari.event/config_reload")
class ConfigReload:
scope: str
key: str
value: Any
old: Optional[Any] = None

__publisher__ = "entari.event/config_reload"
__result_type__: type[bool] = bool


pub = es.define(ConfigReload.__publisher__, ConfigReload)
20 changes: 5 additions & 15 deletions arclet/entari/event/lifespan.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,30 @@
from dataclasses import dataclass

from arclet.letoderea import es
from arclet.letoderea import make_event
from satori.client import Account
from satori.model import LoginStatus


@dataclass
@make_event(name="entari.event/startup")
class Startup:
pass

__publisher__ = "entari.event/startup"


@dataclass
@make_event(name="entari.event/ready")
class Ready:
pass

__publisher__ = "entari.event/ready"


@dataclass
@make_event(name="entari.event/cleanup")
class Cleanup:
pass

__publisher__ = "entari.event/cleanup"


@dataclass
@make_event(name="entari.event/account_update")
class AccountUpdate:
account: Account
status: LoginStatus

__publisher__ = "entari.event/account_update"


es.define("entari.event/startup", Startup)
es.define("entari.event/ready", Ready)
es.define("entari.event/cleanup", Cleanup)
es.define("entari.event/account_update", AccountUpdate)
6 changes: 3 additions & 3 deletions arclet/entari/event/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async def gather(self, context: Contexts):
__result_type__: "type[bool | MessageChain]" = Union[bool, MessageChain]


before_send_pub = es.define(SendRequest.__publisher__, SendRequest)
before_send_pub = es.define(SendRequest)
before_send_pub.bind(provide(MessageChain, target="message"))


Expand All @@ -39,7 +39,7 @@ class SendResponse:
channel: str
message: MessageChain
result: list[MessageReceipt]
session: Union["Session", None] = None
session: Union["Session[SatoriEvent]", None] = None

async def gather(self, context: Contexts):
context["account"] = self.account
Expand All @@ -52,6 +52,6 @@ async def gather(self, context: Contexts):
__publisher__ = "entari.event/send"


send_pub = es.define(SendResponse.__publisher__, SendResponse)
send_pub = es.define(SendResponse)
send_pub.bind(provide(MessageChain, target="message"))
send_pub.bind(provide(list, target="result"))
Loading

0 comments on commit 9a9c9aa

Please sign in to comment.