Skip to content

Commit

Permalink
🎨 format
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Dec 3, 2024
1 parent 57d67e5 commit cff99ab
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 39 deletions.
2 changes: 1 addition & 1 deletion arclet/entari/builtins/auto_reload.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async def watch(self):
if plugin := load_plugin(pid):
logger("INFO", f"Reloaded {plugin.id}")
else:
logger("ERROR",f"Failed to reload {pid}")
logger("ERROR", f"Failed to reload {pid}")

async def launch(self, manager: Launart):
async with self.stage("blocking"):
Expand Down
22 changes: 7 additions & 15 deletions arclet/entari/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
from .config import Config as EntariConfig
from .event.protocol import MessageCreatedEvent, event_parse
from .event.send import SendResponse
from .logger import log
from .plugin import load_plugin
from .plugin.service import plugin_service
from .session import Session, EntariProtocol
from .logger import log
from .session import EntariProtocol, Session


class ApiProtocolProvider(Provider[ApiProtocol]):
Expand Down Expand Up @@ -71,13 +71,9 @@ def from_config(cls, config: EntariConfig | None = None):
configs.append(WebhookInfo(**{k: v for k, v in conf.items() if k != "type"}))
return cls(*configs, log_level=log_level, ignore_self_message=ignore_self_message)

def __init__(
self,
*configs: Config,
log_level: str | int = "INFO",
ignore_self_message: bool = True
):
def __init__(self, *configs: Config, log_level: str | int = "INFO", ignore_self_message: bool = True):
from . import __version__

log.core.opt(colors=True).info(f"Entari <b><c>version {__version__}</c></b>")
super().__init__(*configs, default_api_cls=EntariProtocol)
if not hasattr(EntariConfig, "instance"):
Expand All @@ -102,13 +98,9 @@ def log_msg(event: MessageCreatedEvent):
@es.use(SendResponse.__disp_name__)
async def log_send(event: SendResponse):
if event.session:
log.message.info(
f"[{event.session.channel.name or event.session.channel.id}] <- {event.message!r}"
)
log.message.info(f"[{event.session.channel.name or event.session.channel.id}] <- {event.message!r}")
else:
log.message.info(
f"[{event.channel}] <- {event.message!r}"
)
log.message.info(f"[{event.channel}] <- {event.message!r}")

def on(
self,
Expand Down Expand Up @@ -182,7 +174,7 @@ def __init__(self, origin: type[Service]):
def validate(self, param: Param):
anno = get_origin(param.annotation)
return isinstance(anno, type) and issubclass(anno, self.origin)

async def __call__(self, context: Contexts):
return it(Launart).get_component(self.origin)

Expand Down
6 changes: 3 additions & 3 deletions arclet/entari/event/send.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Union

from arclet.letoderea import es, provide, Contexts
from satori.model import MessageReceipt
from arclet.letoderea import Contexts, es, provide
from satori.client import Account
from satori.model import MessageReceipt

from ..message import MessageChain
from .base import BasedEvent
Expand Down Expand Up @@ -55,4 +55,4 @@ async def gather(self, context: Contexts):

send_pub = es.define(SendResponse.__disp_name__, SendResponse)
send_pub.bind(provide(MessageChain, target="message"))
send_pub.bind(provide(list, target="result"))
send_pub.bind(provide(list, target="result"))
26 changes: 10 additions & 16 deletions arclet/entari/logger.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from __future__ import annotations

import inspect
import logging
import sys
from typing import Union, TYPE_CHECKING, Optional
from typing import TYPE_CHECKING

from loguru import logger

Expand All @@ -11,7 +13,7 @@

class LoggerManager:
def __init__(self):
self.loggers: dict[str, "Logger"] = {}
self.loggers: dict[str, Logger] = {}
self.fork("[core]")
self.fork("[plugin]")
self.fork("[message]")
Expand Down Expand Up @@ -39,15 +41,13 @@ def wrapper(self, name: str, color: str = "blue"):
patched = patched.bind(name=f"plugins.{name}")
self.loggers[f"plugin.{name}"] = patched

def _log(level: str, message: str, exception: Optional[Exception] = None):
patched.opt(colors=True, exception=exception).log(
level, f"| <{color}>{name}</{color}> {message}"
)
def _log(level: str, message: str, exception: Exception | None = None):
patched.opt(colors=True, exception=exception).log(level, f"| <{color}>{name}</{color}> {message}")

return _log

@staticmethod
def set_level(level: Union[str, int]):
def set_level(level: str | int):
if isinstance(level, str):
level = level.upper()
logging.basicConfig(
Expand All @@ -68,15 +68,11 @@ def emit(self, record: logging.LogRecord):
level = record.levelno

frame, depth = inspect.currentframe(), 0
while frame and (
depth == 0 or frame.f_code.co_filename == logging.__file__
):
while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
frame = frame.f_back
depth += 1

logger.opt(depth=depth, exception=record.exc_info).log(
level, record.getMessage()
)
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())


logging.basicConfig(
Expand All @@ -88,9 +84,7 @@ def emit(self, record: logging.LogRecord):

def default_filter(record):
log_level = record["extra"].get("entari_log_level", "INFO")
levelno = (
logger.level(log_level).no if isinstance(log_level, str) else log_level
)
levelno = logger.level(log_level).no if isinstance(log_level, str) else log_level
return record["level"].no >= levelno


Expand Down
8 changes: 6 additions & 2 deletions arclet/entari/plugin/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ def load_plugin(path: str, config: dict | None = None, recursive_guard: set[str]
if referent in recursive_guard:
continue
if referent in plugin_service.plugins:
log.plugin.opt(colors=True).debug(f"reloading <y>{mod.__name__}</y>'s referent <y>{referent!r}</y>")
log.plugin.opt(colors=True).debug(
f"reloading <y>{mod.__name__}</y>'s referent <y>{referent!r}</y>"
)
dispose(referent)
if not load_plugin(referent):
plugin_service._referents[mod.__name__].add(referent)
Expand All @@ -69,7 +71,9 @@ def load_plugin(path: str, config: dict | None = None, recursive_guard: set[str]
except RegisterNotInPluginError as e:
log.plugin.opt(colors=True).error(f"{e.args[0]}")
except Exception as e:
log.plugin.opt(colors=True).exception(f"failed to load plugin <blue>{path!r}</blue> caused by {e!r}", exc_info=e)
log.plugin.opt(colors=True).exception(
f"failed to load plugin <blue>{path!r}</blue> caused by {e!r}", exc_info=e
)


def load_plugins(dir_: str | PathLike | Path):
Expand Down
6 changes: 4 additions & 2 deletions arclet/entari/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from arclet.letoderea import ParsingStop, StepOut, es
from satori.client.account import Account
from satori.client.protocol import ApiProtocol
from satori.element import Element
from satori.const import Api
from satori.element import Element
from satori.model import Channel, Guild, Member, MessageReceipt, PageResult, Role, User

from .event.protocol import Event, FriendRequestEvent, GuildMemberRequestEvent, GuildRequestEvent, MessageEvent
Expand Down Expand Up @@ -52,7 +52,9 @@ async def send_private_message(
channel = await self.user_channel_create(user_id=user_id)
return await self.message_create(channel_id=channel.id, content=message, source=source)

async def message_create(self, channel_id: str, content: str | Iterable[str | Element], source: Event | None = None) -> list[MessageReceipt]:
async def message_create(
self, channel_id: str, content: str | Iterable[str | Element], source: Event | None = None
) -> list[MessageReceipt]:
"""发送消息。返回一个 `MessageReceipt` 对象构成的数组。
Args:
Expand Down

0 comments on commit cff99ab

Please sign in to comment.