Skip to content

Commit

Permalink
fix 0.15.0
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Nov 22, 2022
1 parent 4050bbe commit 6a32c08
Show file tree
Hide file tree
Showing 25 changed files with 153 additions and 126 deletions.
28 changes: 23 additions & 5 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,24 @@ class AdminConfig(BaseModel):
master_name: str
"""bot 的控制者的名字"""

admins: List[str] = Field(default_factory=list)
admins: List[int] = Field(default_factory=list)
"""bot 的管理者(除开控制者)的账号"""


class CommandConfig(BaseModel):
prefix: List[str] = Field(default_factory=lambda x: ["."])
"""命令前缀; At:123456 会转换为 At(123456), Face:xxx 会转换为 Face(name=xxx)"""

help: List[str] = Field(default_factory=lambda x: ["-h", "--help"])
"""帮助选项的名称"""

shortcut: List[str] = Field(default_factory=lambda x: ["-sct", "--shortcut"])
"""快捷命令选项的名称"""

completion: List[str] = Field(default_factory=lambda x: ["-cp", "--comp"])
"""补全选项的名称"""


class PluginConfig(BaseModel):
root: str = Field(default="plugins")
"""模块配置文件的根路径"""
Expand Down Expand Up @@ -77,9 +91,6 @@ class BotConfig(BaseModel):
bot_name: str
"""机器人名字, 请尽量不要与 prefix 重合"""

prefix: List[str] = Field(default_factory=lambda x: ["."])
"""命令前缀; At:123456 会转换为 At(123456), Face:xxx 会转换为 Face(name=xxx)"""

cache_dir: str = Field(default="cache")
"""缓存数据存放的文件夹, 默认为 cache"""

Expand All @@ -89,6 +100,9 @@ class BotConfig(BaseModel):
admin: AdminConfig
"""bot 权限相关配置"""

command: CommandConfig
"""bot 命令相关配置"""

plugin: PluginConfig
"""bot 模块相关配置"""

Expand All @@ -98,14 +112,18 @@ class BotConfig(BaseModel):
tencent: TencentCloudAPIConfig
"""腾讯云相关配置"""

@property
def qq(self) -> int:
return self.mirai.account

@property
def url(self) -> str:
return f"http://{self.mirai.host}:{self.mirai.port}"

@property
def command_prefix(self):
res = []
for p in self.prefix:
for p in self.command.prefix:
if mth := re.match(r"^At:(?P<target>\d+)$", p):
res.append(At(int(mth.groupdict()["target"])))
elif mth := re.match(r"^Face:(?P<target>.+)$", p):
Expand Down
13 changes: 7 additions & 6 deletions app/control.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from typing import Union, Optional

from typing import Union, Optional, Any
from loguru import logger
from graia.broadcast.builtin.decorators import Depend
from graia.broadcast.exceptions import ExecutionStop
from graia.ariadne.model import Friend, Member, Group, MemberPerm
Expand All @@ -9,7 +9,7 @@
from graia.ariadne.app import Ariadne


def require_admin(only: bool = False):
def require_admin(only: bool = False, __record: Any = None):
async def __wrapper__(
app: Ariadne,
sender: Union[Friend, Group],
Expand All @@ -19,8 +19,8 @@ async def __wrapper__(
from .core import RaianBotInterface

bot = app.launch_manager.get_interface(RaianBotInterface)
id_ = id(event) if event else 0
cache = bot.data.cache.setdefault("$admin", set())
id_ = f"{id(event)}" if event else "_"
cache = bot.data.cache.setdefault("$admin", {})
if target.id == bot.config.admin.master_id:
bot.data.cache.pop("$admin", None)
return True
Expand All @@ -36,9 +36,10 @@ async def __wrapper__(
text = (
"权限不足!" if isinstance(sender, Friend) else [At(target.id), Plain("\n权限不足!")]
)
logger.debug(f"permission denied for {sender.id} in {__record}")
if id_ not in cache:
cache.clear()
cache.add(id_)
cache[id_] = True
await Ariadne.current().send_message(sender, MessageChain(text))
raise ExecutionStop

Expand Down
20 changes: 9 additions & 11 deletions app/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import sys
import traceback
from contextlib import ExitStack
from pathlib import Path
from typing import Literal, Set, Type, Union

Expand Down Expand Up @@ -52,13 +51,14 @@ def __init__(self, config: BotConfig):
super().__init__()
self.config = config
self.data = DataInstance.get(None) or BotDataManager()
BotInstance.set(self)

def get_interface(self, _: Type[RaianBotInterface]) -> RaianBotInterface:
return RaianBotInterface()

@property
def required(self) -> Set[Union[str, Type[ExportInterface]]]:
return {"elizabeth.service"}
return set()

@property
def stages(self) -> Set[Literal["preparing", "blocking", "cleanup"]]:
Expand All @@ -69,10 +69,6 @@ def current(cls):
"""获取当前上下文的 Bot"""
return BotInstance.get()

@property
def context(self):
return BotInstance

async def launch(self, manager: Launart):
async with self.stage("preparing"):
try:
Expand All @@ -83,9 +79,7 @@ async def launch(self, manager: Launart):
if not plugin_path.is_dir():
logger.error("插件路径应该为一存在的文件夹")
return
with ExitStack() as stack:
stack.enter_context(BotInstance.use(self))
stack.enter_context(it(Saya).module_context())
with it(Saya).module_context():
for file in plugin_path.iterdir():
name = file.stem if file.is_file() else file.name
if (
Expand Down Expand Up @@ -136,6 +130,10 @@ def launch(debug_log: bool = True):
sys.exit(1)
with namespace("Alconna") as np:
np.headers = config.command_prefix
np.builtin_option_name['help'] = set(config.command.help)
np.builtin_option_name['shortcut'] = set(config.command.shortcut)
np.builtin_option_name['completion'] = set(config.command.completion)

Alconna.config(formatter_type=MarkdownTextFormatter)
saya = it(Saya)
bcc = it(Broadcast)
Expand All @@ -145,11 +143,11 @@ def launch(debug_log: bool = True):
it(GraiaScheduler)
fastapi = FastAPI()
saya.install_behaviours(FastAPIBehaviour(fastapi))
manager.add_service(RaianBotService(config))
manager.add_service(PlaywrightService("chromium", headless=True, auto_download_browser=False, channel="msedge"))
manager.add_service(FastAPIService(fastapi))
manager.add_service(UvicornService(config.api.host, config.api.port))
Ariadne.config(launch_manager=manager, inject_bypass_listener=True)
manager.add_service(RaianBotService(config))
Ariadne.config(launch_manager=manager)
set_output("DEBUG" if debug_log else "INFO")
Ariadne(
connection=conn_cfg(
Expand Down
2 changes: 1 addition & 1 deletion app/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class GroupProfile(BaseProfile):

class UserProfile(BaseProfile):
id: int
trust: int = Field(default=0)
trust: float = Field(default=0)
interact_count: int = Field(default=0)


Expand Down
10 changes: 5 additions & 5 deletions app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ def wrapper(func: T_Callable) -> T_Callable:
return wrapper


@buffer_modifier
def permission(level: Literal["admin", "master"] = "admin") -> BufferModifier:
def wrapper(buffer: Dict[str, Any]) -> None:
buffer.setdefault("decorators", []).append(require_admin(level == "master"))

def permission(level: Literal["admin", "master"] = "admin"):
def wrapper(func: T_Callable) -> T_Callable:
buffer = ensure_buffer(func)
buffer.setdefault("decorators", []).append(require_admin(level == "master", __record=func))
return func
return wrapper


Expand Down
30 changes: 14 additions & 16 deletions assets/data/gacha_arknights.json
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
{
"name": "前路回响",
"six_per": 1,
"five_per": 0.6,
"name": "限定寻访·庆典-斩荆辟路",
"six_per": 0.7,
"five_per": 0.5,
"four_per": 0.45,
"up_limit": [],
"up_alert_limit": [],
"up_limit": [
"缄默德克萨斯"
],
"up_alert_limit": [
"迷迭香",
"浊心斯卡蒂",
"耀骑士临光"
],
"up_five_list": [
"絮雨",
"桑葚",
"洛洛"
"子月"
],
"up_six_list": [
"泥岩",
"琴柳",
"号角"
],
"up_four_list": [
"杰克",
"罗比菈塔",
"褐果"
"斥罪"
],
"up_four_list": [],
"operators": {
"三": [
"空爆",
Expand Down
24 changes: 19 additions & 5 deletions config/bot_config.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
## 机器人名字, 请尽量不要与 prefix 重合
bot_name: "Raian"
## 命令前缀
## At:123456 会转换为 At(123456), Face:xxx 会转换为 Face(name=xxx)
prefix:
- "莱安"
- "At:123456789"
## 缓存数据存放的文件夹, 默认为 cache
cache_dir: 'cache'
## mirai-api-http 相关配置
Expand All @@ -26,6 +21,25 @@ admin:
## bot 的管理者(除开控制者)的账号
admins:
- 111111111
## bot 命令相关配置
command:
## 命令前缀
## At:123456 会转换为 At(123456), Face:xxx 会转换为 Face(name=xxx)
prefix:
- "莱安"
- "At:123456789"
## 帮助选项的名称
help:
- "--help"
- "-h"
## 快捷命令选项的名称
shortcut:
- "--shortcut"
- "-sct"
## 补全选项的名称
completion:
- "--comp"
- "-cp"
## bot 模块相关配置
plugin:
## 模块配置文件的根路径
Expand Down
16 changes: 7 additions & 9 deletions plugins/admin/control.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from pathlib import Path
from typing import List

from app import RaianBotInterface, Sender, permission, create_md, send_handler, RaianBotService
from app import RaianBotInterface, Sender, permission, create_md, send_handler
from arclet.alconna import ArgField, Args, CommandMeta, Option
from arclet.alconna.graia import (
Alconna,
Expand Down Expand Up @@ -150,7 +150,7 @@ async def _m_uninstall(app: Ariadne, sender: Sender, path: Match[str], bot: Raia
@alcommand(module_control, send_error=True)
@permission("master")
@assign("安装")
async def _m_install(app: Ariadne, sender: Sender, path: Match[str], bot: RaianBotService):
async def _m_install(app: Ariadne, sender: Sender, path: Match[str], bot: RaianBotInterface):
saya = it(Saya)
channel_path = path.result if path.available else "admin"
if channel_path.split(".")[-1] == "admin":
Expand All @@ -163,9 +163,8 @@ async def _m_install(app: Ariadne, sender: Sender, path: Match[str], bot: RaianB
if channel_path in saya.channels and channel_path not in bot.config.plugin.disabled:
return await app.send_message(sender, MessageChain("该模组已安装"))
try:
with bot.context.use(bot):
with saya.module_context():
saya.require(channel_path)
with saya.module_context():
saya.require(channel_path)
except Exception as e:
await app.send_message(sender, MessageChain(f"安装 {channel_path} 失败!"))
raise e
Expand All @@ -178,7 +177,7 @@ async def _m_install(app: Ariadne, sender: Sender, path: Match[str], bot: RaianB
@alcommand(module_control, send_error=True)
@permission("master")
@assign("重载")
async def _m_reload(app: Ariadne, sender: Sender, path: Match[str], bot: RaianBotService):
async def _m_reload(app: Ariadne, sender: Sender, path: Match[str], bot: RaianBotInterface):
saya = it(Saya)
channel_path = path.result if path.available else "admin"
if channel_path.split(".")[-1] == "admin":
Expand All @@ -196,9 +195,8 @@ async def _m_reload(app: Ariadne, sender: Sender, path: Match[str], bot: RaianBo
await app.send_message(sender, MessageChain(f"重载 {channel_path} 过程中卸载失败!"))
raise e
try:
with bot.context.use(bot):
with saya.module_context():
saya.require(channel_path)
with saya.module_context():
saya.require(channel_path)
except Exception as e:
await app.send_message(sender, MessageChain(f"重载 {channel_path} 过程中安装失败!"))
raise e
Expand Down
4 changes: 2 additions & 2 deletions plugins/admin/flash.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from app import BotConfig
from graia.ariadne import Ariadne
from graia.ariadne.event.message import MessageEvent
from graia.ariadne.event.message import GroupMessage, FriendMessage
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import FlashImage
from graiax.shortcut.saya import listen


@listen(MessageEvent)
@listen(GroupMessage, FriendMessage)
async def _flash(app: Ariadne, message: MessageChain, config: BotConfig):
if not message.has(FlashImage):
return
Expand Down
4 changes: 2 additions & 2 deletions plugins/admin/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from app import RaianBotInterface
from graia.ariadne import Ariadne
from graia.ariadne.event.lifecycle import ApplicationLaunched
from graia.ariadne.event.lifecycle import AccountLaunch
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.model.relationship import Group
from graiax.shortcut.saya import listen
Expand All @@ -12,7 +12,7 @@
from ..config.admin import AdminConfig


@listen(ApplicationLaunched)
@listen(AccountLaunch)
async def _report(app: Ariadne, interface: RaianBotInterface):
data = interface.data
config = interface.config
Expand Down
6 changes: 3 additions & 3 deletions plugins/coc.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
from nepattern import BasePattern, Bind
from arclet.alconna import Args, Arpamar, CommandMeta, namespace, Empty
from arclet.alconna.graia import Alconna, alcommand, AtID, Match
from graia.ariadne.event.lifecycle import ApplicationShutdown
from graia.ariadne.util.saya import listen
from graia.ariadne.event.lifecycle import AccountShutdown
from graiax.shortcut.saya import listen
from graia.ariadne.model import Group
from graia.ariadne.app import Ariadne
from contextlib import suppress
Expand Down Expand Up @@ -242,6 +242,6 @@ async def del_handle(app: Ariadne, sender: Sender, target: Target, data: Match[T
return await app.send_message(sender, "\n".join(res))


@listen(ApplicationShutdown)
@listen(AccountShutdown)
async def _save():
card.save()
4 changes: 2 additions & 2 deletions plugins/code_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from graia.ariadne.event.message import FriendMessage, GroupMessage
from graia.ariadne.message.chain import MessageChain
from graia.ariadne.message.element import Image
from graia.ariadne.util.saya import listen
from graiax.shortcut.saya import listen

code = Alconna(
"执行",
Expand All @@ -30,7 +30,7 @@


@shortcuts(
命令概览=MessageChain("渊白执行\nfrom arclet.alconna import command_manager\nprint(command_manager)"), # type: ignore
命令概览=MessageChain(f"{code.headers[0]}执行\nfrom arclet.alconna import command_manager\nprint(command_manager)"), # type: ignore
)
@alcommand(code, send_error=True)
@permission("admin")
Expand Down
Loading

0 comments on commit 6a32c08

Please sign in to comment.