From 6a32c08a85eef42f124228868fce1bfadfca3b14 Mon Sep 17 00:00:00 2001 From: RF-Tar-Railt <3165388245@qq.com> Date: Tue, 22 Nov 2022 15:18:30 +0800 Subject: [PATCH] fix 0.15.0 --- app/config.py | 28 ++++++++++++++++++----- app/control.py | 13 ++++++----- app/core.py | 20 ++++++++--------- app/data.py | 2 +- app/utils.py | 10 ++++----- assets/data/gacha_arknights.json | 30 ++++++++++++------------- config/bot_config.yml | 24 +++++++++++++++----- plugins/admin/control.py | 16 ++++++-------- plugins/admin/flash.py | 4 ++-- plugins/admin/start.py | 4 ++-- plugins/coc.py | 6 ++--- plugins/code_exec.py | 4 ++-- plugins/dialog.py | 2 +- plugins/gacha.py | 2 +- plugins/guess_operator.py | 4 ++-- plugins/help.py | 38 +++++++++++++++----------------- plugins/learn_repeat.py | 2 +- plugins/nudge.py | 2 +- plugins/role.py | 14 ++++++------ plugins/setu.py | 24 ++++++++++---------- plugins/sign.py | 3 ++- plugins/status.py | 4 ++-- plugins/weibo_fetch.py | 19 ++++++++-------- pyproject.toml | 2 +- requirements.txt | 2 +- 25 files changed, 153 insertions(+), 126 deletions(-) diff --git a/app/config.py b/app/config.py index 7cdd702..d3b0079 100644 --- a/app/config.py +++ b/app/config.py @@ -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") """模块配置文件的根路径""" @@ -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""" @@ -89,6 +100,9 @@ class BotConfig(BaseModel): admin: AdminConfig """bot 权限相关配置""" + command: CommandConfig + """bot 命令相关配置""" + plugin: PluginConfig """bot 模块相关配置""" @@ -98,6 +112,10 @@ 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}" @@ -105,7 +123,7 @@ def url(self) -> str: @property def command_prefix(self): res = [] - for p in self.prefix: + for p in self.command.prefix: if mth := re.match(r"^At:(?P\d+)$", p): res.append(At(int(mth.groupdict()["target"]))) elif mth := re.match(r"^Face:(?P.+)$", p): diff --git a/app/control.py b/app/control.py index de0800b..d24ee15 100644 --- a/app/control.py +++ b/app/control.py @@ -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 @@ -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], @@ -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 @@ -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 diff --git a/app/core.py b/app/core.py index 01329c1..72c0730 100644 --- a/app/core.py +++ b/app/core.py @@ -1,6 +1,5 @@ import sys import traceback -from contextlib import ExitStack from pathlib import Path from typing import Literal, Set, Type, Union @@ -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"]]: @@ -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: @@ -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 ( @@ -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) @@ -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( diff --git a/app/data.py b/app/data.py index 8003dfe..6d849fd 100644 --- a/app/data.py +++ b/app/data.py @@ -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) diff --git a/app/utils.py b/app/utils.py index ddf8a02..732e81a 100644 --- a/app/utils.py +++ b/app/utils.py @@ -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 diff --git a/assets/data/gacha_arknights.json b/assets/data/gacha_arknights.json index d66d4de..7dd0cbd 100644 --- a/assets/data/gacha_arknights.json +++ b/assets/data/gacha_arknights.json @@ -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": { "三": [ "空爆", diff --git a/config/bot_config.yml b/config/bot_config.yml index a1b879d..35fc66e 100644 --- a/config/bot_config.yml +++ b/config/bot_config.yml @@ -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 相关配置 @@ -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: ## 模块配置文件的根路径 diff --git a/plugins/admin/control.py b/plugins/admin/control.py index 2c2383f..da3aab2 100644 --- a/plugins/admin/control.py +++ b/plugins/admin/control.py @@ -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, @@ -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": @@ -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 @@ -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": @@ -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 diff --git a/plugins/admin/flash.py b/plugins/admin/flash.py index 4039ee0..2f7cd36 100644 --- a/plugins/admin/flash.py +++ b/plugins/admin/flash.py @@ -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 diff --git a/plugins/admin/start.py b/plugins/admin/start.py index 027829f..093563a 100644 --- a/plugins/admin/start.py +++ b/plugins/admin/start.py @@ -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 @@ -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 diff --git a/plugins/coc.py b/plugins/coc.py index 706f8db..0d2564b 100644 --- a/plugins/coc.py +++ b/plugins/coc.py @@ -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 @@ -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() diff --git a/plugins/code_exec.py b/plugins/code_exec.py index 5e67e05..f88aa4a 100644 --- a/plugins/code_exec.py +++ b/plugins/code_exec.py @@ -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( "执行", @@ -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") diff --git a/plugins/dialog.py b/plugins/dialog.py index 6462e14..148929e 100644 --- a/plugins/dialog.py +++ b/plugins/dialog.py @@ -12,7 +12,7 @@ from graia.ariadne.event.message import GroupMessage, FriendMessage from graia.ariadne.app import Ariadne from graia.ariadne.model import Friend, Group -from graia.ariadne.util.saya import listen, priority, dispatch +from graiax.shortcut.saya import listen, priority, dispatch from graia.ariadne.util.cooldown import CoolDown from graia.broadcast.exceptions import PropagationCancelled diff --git a/plugins/gacha.py b/plugins/gacha.py index d779531..82af0c5 100644 --- a/plugins/gacha.py +++ b/plugins/gacha.py @@ -9,7 +9,7 @@ from graia.ariadne.message.chain import MessageChain from graia.ariadne.message.element import Image from graia.ariadne.util.cooldown import CoolDown -from graia.ariadne.util.saya import dispatch, listen +from graiax.shortcut.saya import dispatch, listen from graiax.fastapi import route from plugins.config.gacha import GachaConfig diff --git a/plugins/guess_operator.py b/plugins/guess_operator.py index d5bccbf..1470aae 100644 --- a/plugins/guess_operator.py +++ b/plugins/guess_operator.py @@ -18,7 +18,7 @@ Args["max_guess", int, 8], Args["simple;K", bool, False], Option("更新", Args["name;S", str]), - Option("提示"), + Option("规则"), Option("重置"), meta=CommandMeta("明日方舟猜干员游戏", usage="可以指定最大猜测次数"), ) @@ -26,7 +26,7 @@ @alcommand(alc) @record("猜干员") -@assign("提示") +@assign("规则") async def guess_info(app: Ariadne, sender: Sender): image = Path("assets/image/guess.png").open("rb").read() return await app.send_message(sender, MessageChain(Image(data_bytes=image))) diff --git a/plugins/help.py b/plugins/help.py index 7162455..d643c0a 100644 --- a/plugins/help.py +++ b/plugins/help.py @@ -8,21 +8,23 @@ from graiax.text2img.playwright.builtin import MarkdownToImg -@shortcuts(菜单=MessageChain("渊白帮助")) -@alcommand( - Alconna( - "帮助", - Args[ - "query;OH#选择某条命令的id或者名称查看具体帮助", - str, - ArgField( - -1, - completion=lambda: f"试试 {random.randint(0, len(command_manager.get_commands()))}", - ), - ], - meta=CommandMeta("查看帮助"), - ) +cmd_help = Alconna( + "帮助", + Args[ + "query;OH#选择某条命令的id或者名称查看具体帮助", + str, + ArgField( + -1, + completion=lambda: f"试试 {random.randint(0, len(command_manager.get_commands()))}", + ), + ], + meta=CommandMeta("查看帮助"), ) + + + +@shortcuts(菜单=MessageChain(f"{cmd_help.headers[0]}帮助")) +@alcommand(cmd_help) async def send_help(app: Ariadne, sender: Sender, query: Match[str], bot: RaianBotInterface): if not query.available: md = f"""\ @@ -49,9 +51,7 @@ async def send_help(app: Ariadne, sender: Sender, query: Match[str], bot: RaianB "\n\n* 想给点饭钱的话,这里有赞助链接:https://afdian.net/@rf_tar_railt" "\n\n* 更多功能待开发,如有特殊需求可以向 3165388245 询问, 或前往 122680593 交流" ) - return await app.send_message( - sender, MessageChain(Image(data_bytes=await MarkdownToImg().render(md))) - ) + return await app.send_message(sender, MessageChain(Image(data_bytes=await MarkdownToImg().render(md)))) try: if query.result.isdigit(): cmds = list(command_manager.all_command_raw_help().keys()) @@ -64,8 +64,6 @@ async def send_help(app: Ariadne, sender: Sender, query: Match[str], bot: RaianB ) ) text = command_manager.get_command(cmds[0]).get_help() - return await app.send_message( - sender, await send_handler(text) - ) + return await app.send_message(sender, await send_handler(text)) except (IndexError, TypeError): return await app.send_message(sender, MessageChain("查询失败!")) diff --git a/plugins/learn_repeat.py b/plugins/learn_repeat.py index 6f0a434..1d783b4 100644 --- a/plugins/learn_repeat.py +++ b/plugins/learn_repeat.py @@ -11,7 +11,7 @@ from graia.ariadne.message.element import Image, At, Source, Plain, Face, ForwardNode, Forward from graia.ariadne.model import Group, Member from graia.ariadne.exception import UnknownTarget, UnknownError -from graia.ariadne.util.saya import listen, priority +from graiax.shortcut.saya import listen, priority from graia.broadcast.exceptions import PropagationCancelled from contextlib import suppress diff --git a/plugins/nudge.py b/plugins/nudge.py index f94ea4a..54aef3c 100644 --- a/plugins/nudge.py +++ b/plugins/nudge.py @@ -5,7 +5,7 @@ from graia.ariadne.event.mirai import NudgeEvent from graia.ariadne.model import Group, Member from graia.ariadne.app import Ariadne -from graia.ariadne.util.saya import listen +from graiax.shortcut.saya import listen from app import RaianBotInterface, record from library.petpet import PetGenerator diff --git a/plugins/role.py b/plugins/role.py index a05fc51..781b961 100644 --- a/plugins/role.py +++ b/plugins/role.py @@ -119,13 +119,13 @@ async def _r_remove( if _tag not in _roles.data: return await app.send_group_message(sender, MessageChain(f"分组 {_tag} 不存在")) if not targets.available or not targets.result: - del roles.data[_tag] - return await app.send_group_message(sender, MessageChain(f"分组 {_tag} 删除成功")) - - data = _roles.data[_tag].copy() - for i in filter(lambda x: x.target in data, targets.result): - _roles.data[_tag].remove(i.target) - await app.send_group_message(sender, MessageChain(f"分组 {_tag} 清理成功")) + del _roles.data[_tag] + await app.send_group_message(sender, MessageChain(f"分组 {_tag} 删除成功")) + else: + data = _roles.data[_tag].copy() + for i in filter(lambda x: x.target in data, targets.result): + _roles.data[_tag].remove(i.target) + await app.send_group_message(sender, MessageChain(f"分组 {_tag} 清理成功")) group.set(_roles) bot.data.update_group(group) diff --git a/plugins/setu.py b/plugins/setu.py index ba537cb..e9b6259 100644 --- a/plugins/setu.py +++ b/plugins/setu.py @@ -4,7 +4,7 @@ from graia.ariadne.message.element import Image from graia.ariadne.app import Ariadne -from app import record, Sender, Target +from app import record, Sender setu = Alconna( "涩图", @@ -16,30 +16,30 @@ @alcommand(setu) @record('setu') -async def send_setu(app: Ariadne, target: Target, sender: Sender, result: Arpamar): +async def send_setu(app: Ariadne, sender: Sender, result: Arpamar): """随机涩图发送""" - data={"r18": 2 if result.find("r18") else 0} + print(sender) + data = {"r18": 2 if result.find("r18") else 0} if result.find("tag"): data["tag"] = list(result.query_with(tuple, "tag.tags", ())) async with app.service.client_session.post( - "https://api.lolicon.app/setu/v2?", - headers={"Content-type": "application/json", "accept": "application/json"}, - json=data, - timeout=20, + "https://api.lolicon.app/setu/v2?", + headers={"Content-type": "application/json", "accept": "application/json"}, + json=data, + timeout=20, ) as resp: res = await resp.json() if res.get("error"): return await app.send_message(sender, MessageChain("网路出错了!呜")) - - async with app.service.client_session.get( - f"https://pixiv.re/{res['data'][0]['pid']}.{res['data'][0]['ext']}" - ) as img: - bts = await img.read() await app.send_message(sender, MessageChain( f"标题:{res['data'][0]['title']}\n" f"pid:{res['data'][0]['pid']}\n" f"tags:{', '.join(res['data'][0]['tags'][:4])}" )) + async with app.service.client_session.get( + f"https://pixiv.re/{res['data'][0]['pid']}.{res['data'][0]['ext']}" + ) as img: + bts = await img.read() res = await app.send_message(sender, MessageChain(Image(data_bytes=bts))) if res.id < 0: return await app.send_message(sender, MessageChain("图片发不出来,抱歉。。")) diff --git a/plugins/sign.py b/plugins/sign.py index 9cb3865..13285fb 100644 --- a/plugins/sign.py +++ b/plugins/sign.py @@ -1,3 +1,4 @@ +import random from datetime import datetime from typing import NamedTuple from arclet.alconna import CommandMeta @@ -42,7 +43,7 @@ async def sign_up(app: Ariadne, sender: Group, member: Member, source: Source, b ) user.set(sign_info(today.month, today.day)) if user.trust < int(bot.config.plugin.get(SignConfig).max): - user.trust += 1 + user.trust += (random.randint(1, 10) / 6.25) await app.send_group_message( sender, MessageChain(f"签到成功!\n当前信赖值:{user.trust}"), quote=source.id diff --git a/plugins/status.py b/plugins/status.py index 86b03e8..1a89b07 100644 --- a/plugins/status.py +++ b/plugins/status.py @@ -7,7 +7,7 @@ from graia.ariadne.message.chain import MessageChain from graia.ariadne.message.element import Image from graia.ariadne.event.message import GroupMessage, FriendMessage -from graia.ariadne.util.saya import listen +from graiax.shortcut.saya import listen from app import permission, Sender, create_image @@ -21,8 +21,8 @@ @listen(GroupMessage, FriendMessage) -@startswith("/状态|/设备信息|/status") @permission("admin") +@startswith("/状态|/设备信息|/status") async def status(app: Ariadne, sender: Sender): p = psutil.Process(pid) started_time = time.localtime(p.create_time()) diff --git a/plugins/weibo_fetch.py b/plugins/weibo_fetch.py index 365a116..f62c09f 100644 --- a/plugins/weibo_fetch.py +++ b/plugins/weibo_fetch.py @@ -110,9 +110,9 @@ async def get_fetch(user: str, index: int = -1, page: int = 1, jump: bool = Fals ) +@alcommand(weibo_fetch) @record("微博功能") @assign("动态") -@alcommand(weibo_fetch) async def wfetch( app: Ariadne, target: Target, sender: Sender, source: Source, user: Match[str], index: Match[int], page: Match[int] @@ -130,9 +130,9 @@ async def wfetch( return await app.send_message(sender, MessageChain("获取失败啦")) +@alcommand(weibo_fetch) @record("微博功能") @assign("follow") -@alcommand(weibo_fetch) async def wfollow(app: Ariadne, sender: Sender, source: Source, user: Match[str]): if isinstance(sender, Friend): return @@ -149,9 +149,9 @@ async def wfollow(app: Ariadne, sender: Sender, source: Source, user: Match[str] return await app.send_message(sender, MessageChain(f"关注 {follower.name} 成功!"), quote=source.id) +@alcommand(weibo_fetch) @record("微博功能") @assign("unfollow") -@alcommand(weibo_fetch) async def wunfollow(app: Ariadne, sender: Sender, source: Source, user: Match[str]): if isinstance(sender, Friend): return @@ -168,16 +168,16 @@ async def wunfollow(app: Ariadne, sender: Sender, source: Source, user: Match[st return await app.send_message(sender, MessageChain(f"解除关注 {follower.name} 成功!"), quote=source.id) +@alcommand(weibo_fetch) @record("微博功能") @assign("list") -@alcommand(weibo_fetch) async def wlist(app: Ariadne, target: Target, sender: Sender, source: Source): if isinstance(sender, Friend): return if not bot.data.exist(sender.id): return prof = bot.data.get_group(sender.id) - if not (followers := prof.get(weibo_followers)): + if not (followers := prof.get(weibo_followers)) or not followers.data: return await app.send_message(sender, "当前群组不存在微博关注对象") nodes = [] notice = None @@ -206,8 +206,9 @@ async def wlist(app: Ariadne, target: Target, sender: Sender, source: Source): @every(1, "minute") @record("微博动态自动获取", False) async def update(): + app = Ariadne.current() dynamics = {} - browser: PlaywrightBrowser = bot.app.launch_manager.get_interface(PlaywrightBrowser) + browser: PlaywrightBrowser = app.launch_manager.get_interface(PlaywrightBrowser) async with browser.page(viewport={"width": 800, "height": 2400}) as page: for gid in bot.data.groups: prof = bot.data.get_group(int(gid)) @@ -223,13 +224,13 @@ async def update(): data, name = dynamics[uid] elif res := await api.update(int(uid)): dynamics[uid] = ( - data := await _handle_dynamic(page, res, now, bot.config.account, bot.config.bot_name), + data := await _handle_dynamic(page, res, now, bot.config.qq, bot.config.bot_name), name := res.user.name ) else: continue - await bot.app.send_group_message(prof.id, MessageChain(f"{name} 有一条新动态!请查收!")) - await bot.app.send_group_message(prof.id, MessageChain( + await app.send_group_message(prof.id, MessageChain(f"{name} 有一条新动态!请查收!")) + await app.send_group_message(prof.id, MessageChain( Forward(*data) )) except (ValueError, TypeError, IndexError, KeyError): diff --git a/pyproject.toml b/pyproject.toml index 78104d5..96f5122 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -6,7 +6,7 @@ authors = [ {name = "RF-Tar-Railt", email = "rf_tar_railt@qq.com"}, ] dependencies = [ - "arclet-alconna<2.0.0, >=1.3.2", + "arclet-alconna<2.0.0, >=1.3.2.2", "arclet-alconna-graia<1.0.0, >=0.9.0", "arclet-alconna-tools>=0.2.1", "graia-ariadne<0.10.0, >=0.9.4", diff --git a/requirements.txt b/requirements.txt index 9555e1d..312c55f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -arclet-alconna<2.0.0, >=1.3.2 +arclet-alconna<2.0.0, >=1.3.2.2 arclet-alconna-graia<1.0.0, >=0.9.0 arclet-alconna-tools>=0.2.1 graia-ariadne<0.10.0, >=0.9.4