指令ban|unban改为pm ban|unban,新增指令pm set设置配置项

This commit is contained in:
CMHopeSunshine 2022-08-26 12:54:27 +08:00
parent f5c5d3d1ba
commit 70c7a46214
11 changed files with 97 additions and 36 deletions

View File

@ -5,8 +5,8 @@ from LittlePaimon.manager.plugin_manager import plugin_manager
app: FastAPI = nonebot.get_app()
if plugin_manager.get_config('启用CookieWeb', False):
if plugin_manager.config.CookieWeb_enable:
from pywebio.platform.fastapi import webio_routes
from .bind_cookie import bind_cookie_page
logger.info('原神Cookie', f'<g>启用CookieWeb成功</g>{plugin_manager.get_config("CookieWeb地址")}')
logger.info('原神Cookie', f'<g>启用CookieWeb成功,地址{plugin_manager.config.CookieWeb_url}</g>')
app.mount('/LittlePaimon/cookie', FastAPI(routes=webio_routes(bind_cookie_page)))

View File

@ -3,9 +3,10 @@ import asyncio
from nonebot import on_regex, on_command
from nonebot.matcher import Matcher
from nonebot.exception import IgnoredException
from nonebot.params import RegexDict
from nonebot.params import RegexDict, CommandArg
from nonebot.permission import SUPERUSER
from nonebot.message import run_preprocessor
from nonebot.adapters.onebot.v11 import GroupMessageEvent, PrivateMessageEvent, MessageEvent
from nonebot.adapters.onebot.v11 import Message, GroupMessageEvent, PrivateMessageEvent, MessageEvent
from nonebot.typing import T_State
from LittlePaimon import SUPERUSERS, DRIVER
@ -16,8 +17,9 @@ from .draw_help import draw_help
plugin_manager = PluginManager()
manage_cmd = on_regex(r'^(?P<func>ban|unban) (?P<plugin>([\w ]*)|all) ?(-g (?P<group>[\d ]*) ?)?(-u (?P<user>[\d ]*) ?)?(?P<reserve>-r)?', priority=1)
help_cmd = on_command('help', aliases={'帮助', '菜单'}, priority=1)
manage_cmd = on_regex(r'^pm (?P<func>ban|unban) (?P<plugin>([\w ]*)|all) ?(-g (?P<group>[\d ]*) ?)?(-u (?P<user>[\d ]*) ?)?(?P<reserve>-r)?', priority=1)
help_cmd = on_command('help', aliases={'帮助', '菜单', 'pm help'}, priority=1)
set_config_cmd = on_command('pm set', priority=1, permission=SUPERUSER)
@manage_cmd.handle()
@ -86,6 +88,16 @@ async def _(event: MessageEvent):
await help_cmd.finish(img)
@set_config_cmd.handle()
async def _(event: MessageEvent, msg: Message = CommandArg()):
msg = msg.extract_plain_text().strip().split(' ')
if len(msg) != 2:
await set_config_cmd.finish('参数错误用法pm set 配置名 配置值')
else:
result = plugin_manager.set_config(msg[0], msg[1])
await set_config_cmd.finish(result)
@DRIVER.on_bot_connect
async def _():
await plugin_manager.init_plugins()

View File

@ -7,7 +7,7 @@ from LittlePaimon.utils import logger
from LittlePaimon.config.path import PLUGIN_CONFIG, PAIMON_CONFIG
from LittlePaimon.utils.files import load_yaml, save_yaml
from LittlePaimon.database.models import PluginPermission
from .model import MatcherInfo, PluginInfo
from .model import MatcherInfo, PluginInfo, Config
hidden_plugins = [
'LittlePaimon',
@ -24,13 +24,14 @@ class PluginManager:
self.plugin_config_path = PLUGIN_CONFIG
self.config_path = PAIMON_CONFIG
self.data: Dict[str, PluginInfo] = {}
self.config: Dict[str, any] = {}
self.config: Config = Config()
self.load()
def save(self):
"""
保存数据
"""
save_yaml(self.config.dict(by_alias=True), self.config_path)
for name, plugin in self.data.items():
save_yaml(plugin.dict(), self.plugin_config_path / f'{name}.yml')
@ -39,34 +40,34 @@ class PluginManager:
读取配置项以及插件数据
"""
if self.config_path.exists():
self.config = load_yaml(self.config_path)
else:
logger.warning('插件管理器', '<r>无法读取配置文件</r>,请检查是否已将<m>config/paimon_config_default.yml</m>复制为<m>config/paimon_config.yml</m>')
self.config = Config.parse_obj(load_yaml(self.config_path))
# else:
# logger.warning('插件管理器', '<r>无法读取配置文件</r>,请检查是否已将<m>config/paimon_config_default.yml</m>复制为<m>config/paimon_config.yml</m>')
for file in self.plugin_config_path.iterdir():
if file.is_file() and file.name.endswith('.yml'):
data = load_yaml(file)
self.data[file.name.replace('.yml', '')] = PluginInfo.parse_obj(data)
def get_config(self, config_name: str, default: any = None):
def set_config(self, config_name: str, value: any):
"""
获取派蒙配置项
设置派蒙配置项
:param config_name: 配置名
:param default: 无配置时的默认值
:return: 配置项
:param value: 新配置值
"""
return self.config.get(config_name, default)
if config_name not in self.config.dict(by_alias=True).keys():
return f'没有配置项为{config_name}'
if '启用' in config_name or '开关' in config_name:
if value not in ['', '', 'true', 'false', 'on', 'off']:
return '参数错误'
value = value in ['', 'true', 'on']
elif config_name != 'CookieWeb地址' and not value.isdigit():
return '配置项不合法,必须为数字'
temp = self.config.dict(by_alias=True)
temp[config_name] = value
self.config = Config.parse_obj(temp)
self.save()
return f'成功设置{config_name}{value}'
def get_plugin_config(self, plugin_name: str, config_name: str, default: any = None):
"""
获取派蒙插件配置项
:param plugin_name插件名
:param config_name: 配置名
:param default: 无配置时的默认值
:return: 配置项
"""
if plugin_name in self.data and self.data[plugin_name].configs:
return self.data[plugin_name].configs.get(config_name, default)
return default
async def init_plugins(self):
plugin_list = nb_plugin.get_loaded_plugins()

View File

@ -1,6 +1,6 @@
from typing import Optional, List
from pydantic import BaseModel
from pydantic import BaseModel, Field
class MatcherInfo(BaseModel):
@ -35,3 +35,24 @@ class PluginInfo(BaseModel):
"""插件配置项"""
matchers: Optional[List[MatcherInfo]] = []
"""命令列表"""
class Config(BaseModel):
CookieWeb_enable: bool = Field(True, alias='启用CookieWeb')
CookieWeb_url: str = Field('http://127.0.0.1:13579/LittlePaimon/cookie', alias='CookieWeb地址')
sim_gacha_cd_group: int = Field(30, alias='模拟抽卡群冷却')
sim_gacha_cd_member: int = Field(60, alias='模拟抽卡群冷却')
auto_myb_enable: bool = Field(True, alias='米游币自动获取开关')
auto_myb_hour: int = Field(8, alias='米游币开始执行时间(小时)')
auto_myb_minute: int = Field(0, alias='米游币开始执行时间(分钟)')
auto_sign_enable: bool = Field(True, alias='米游社自动签到开关')
auto_sign_hour: int = Field(0, alias='米游社签到开始时间(小时)')
auto_sign_minute: int = Field(5, alias='米游社签到开始时间(分钟)')
ssbq_enable: bool = Field(True, alias='实时便签检查开关')
ssbq_begin: int = Field(0, alias='实时便签停止检查开始时间')
ssbq_end: int = Field(6, alias='实时便签停止检查结束时间')
ssbq_check: int = Field(16, alias='实时便签检查间隔')

View File

@ -61,6 +61,7 @@ async def _(event: Union[GroupMessageEvent, PrivateMessageEvent], uid=CommandUID
if f'{event.user_id}-{uid}' in signing_list:
await sign.finish('你已经在执行签到任务中,请勿重复发送', at_sender=True)
else:
await sign.send(f'开始为UID{uid}执行米游社签到,请稍等...', at_sender=True)
logger.info('米游社原神签到', '', {'user_id': event.user_id, 'uid': uid, '执行签到': ''})
signing_list.append(f'{event.user_id}-{uid}')
_, result = await mhy_bbs_sign(str(event.user_id), uid)
@ -104,6 +105,7 @@ async def _(event: Union[GroupMessageEvent, PrivateMessageEvent], uid=CommandUID
if f'{event.user_id}-{uid}' in coin_getting_list:
await get_coin.finish('你已经在执行米游币获取任务中,请勿重复发送', at_sender=True)
else:
await get_coin.send(f'开始为UID{uid}执行米游币获取,请稍等...', at_sender=True)
logger.info('米游币自动获取', '', {'user_id': event.user_id, 'uid': uid, '执行获取': ''})
coin_getting_list.append(f'{event.user_id}-{uid}')
result = await mhy_bbs_coin(str(event.user_id), uid)

View File

@ -289,11 +289,13 @@ async def mhy_bbs_coin(user_id: str, uid: str) -> str:
return msg if result else f'UID{uid}{msg}'
@scheduler.scheduled_job('cron', hour=pm.get_plugin_config('Paimon_Autobbs', '米游币开始小时', 0), minute=pm.get_plugin_config('Paimon_Autobbs', '米游币开始分钟', 0), misfire_grace_time=10)
@scheduler.scheduled_job('cron', hour=pm.config.auto_myb_hour, minute=pm.config.auto_myb_minute, misfire_grace_time=10)
async def bbs_auto_coin():
"""
指定时间执行所有米游币获取订阅任务 并将结果分群绘图发送
"""
if not pm.config.auto_myb_enable:
return
t = time.time()
subs = await MihoyoBBSSub.filter(sub_event='米游币自动获取').all()
if not subs:

View File

@ -55,7 +55,7 @@ async def mhy_bbs_sign(user_id: str, uid: str) -> Tuple[SignResult, str]:
return SignResult.FAIL, f'{uid}签到失败,无法绕过验证码'
@scheduler.scheduled_job('cron', hour=pm.get_plugin_config('Paimon_Autobbs', '签到开始小时', 0), minute=pm.get_plugin_config('Paimon_Autobbs', '签到开始分钟', 5), misfire_grace_time=10)
@scheduler.scheduled_job('cron', hour=pm.config.auto_sign_hour, minute=pm.config.auto_sign_minute, misfire_grace_time=10)
async def _():
await bbs_auto_sign()
@ -64,6 +64,8 @@ async def bbs_auto_sign():
"""
指定时间执行所有米游社原神签到任务 并将结果分群绘图发送
"""
if not pm.config.auto_sign_enable:
return
t = time.time() # 计时用
subs = await MihoyoBBSSub.filter(sub_event='米游社原神签到').all()
if not subs:

View File

@ -95,9 +95,9 @@ async def _(event: MessageEvent, msg: Message = CommandArg()):
else:
logger.info('原神Cookie', '', {'用户': str(event.user_id)}, '绑定失败cookie已失效', False)
await ysb.finish('这个cookie无效请确认是否正确\n获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n', at_sender=True)
elif pm.get_config('启用CookieWeb', False):
elif pm.config.CookieWeb_enable:
await ysb.finish(
f'获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n获取后,使用[ysb cookie]指令绑定或前往{pm.get_config("CookieWeb地址")}网页添加绑定',
f'获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n获取后,使用[ysb cookie]指令绑定或前往{pm.config.CookieWeb_url}网页添加绑定',
at_sender=True)
else:
await ysb.finish('获取cookie的教程\ndocs.qq.com/doc/DQ3JLWk1vQVllZ2Z1\n获取后,使用[ysb cookie]指令绑定',

View File

@ -67,10 +67,12 @@ async def handle_ssbq(player: Player):
return f'{player.uid}绘制图片失败,{e}\n'
@scheduler.scheduled_job('cron', minute=f'*/{pm.get_plugin_config("Paimon_DailyNote", "检查间隔", 16)}', misfire_grace_time=10)
@scheduler.scheduled_job('cron', minute=f'*/{pm.config.ssbq_check}', misfire_grace_time=10)
async def check_note():
if not pm.config.ssbq_enable:
return
# 0点到6点间不做检查
if 0 <= datetime.datetime.now().hour <= 6:
if pm.config.ssbq_begin <= datetime.datetime.now().hour <= pm.config.ssbq_end:
return
t = time.time()
subs = await DailyNoteSub.all()

View File

@ -77,8 +77,8 @@ async def _(event: MessageEvent, reGroup: Dict = RegexDict()):
pool = pool or '角色1'
result = await draw_gacha_img(event.user_id, pool, num, nickname)
if isinstance(event, GroupMessageEvent):
freq_limiter.start(f'gacha-group{event.group_id}', pm.get_plugin_config('Paimon_Gacha', '群冷却', 30))
freq_limiter.start(f'gacha-group{event.group_id}-{event.user_id}', pm.get_plugin_config('Paimon_Gacha', '群员冷却', 60))
freq_limiter.start(f'gacha-group{event.group_id}', pm.config.sim_gacha_cd_group)
freq_limiter.start(f'gacha-group{event.group_id}-{event.user_id}', pm.config.sim_gacha_cd_member)
await sim_gacha.finish(result)

View File

@ -1,4 +1,23 @@
# 这个文件是派蒙相关配置项的默认值你可以在启动前将本文件复制一份删除_default后缀然后修改配置项。若不修改启动后也会自动根据默认值生成一份文件。
# 你可以向机器人使用[pm set 配置名 配置值]来动态修改配置项。
启用CookieWeb: false
# 是否启用绑定Cookie的网页UI
CookieWeb地址: http://127.0.0.1:13579/LittlePaimon/cookie
# CookieWeb的地址如要公网访问请修改公网ip如需使用nginx等反代请参考https://pywebio.readthedocs.io/zh_CN/latest/misc.html?highlight=nginx#nginx-websocket-config-example进行配置
模拟抽卡群冷却: 30 # 群冷却时间,单位秒
模拟抽卡群成员冷却: 60 # 群成员冷却时间,单位秒
米游币自动获取开关: true # 是否自动获取米游币
米游币开始执行时间(小时): 8 # 开始执行没米游币自动获取的时间
米游币开始执行时间(分钟): 0 # 开始执行没米游币自动获取的时间
米游社自动签到开关: true # 是否开启米游社自动签到
米游社签到开始时间(小时): 0 # 开始执行没米游社原神自动的时间
米游社签到开始时间(分钟): 5 # 开始执行没米游社原神自动的时间
实时便签检查开关: true # 是否开启实时便签检查
实时便签检查间隔: 16 # 实时便签检查间隔,单位分钟
实时便签停止检查开始时间: 0
实时便签停止检查结束时间: 6 # 处于这个时间段的时候停止检查