Archived
1
0
Fork 0

new feature: type check for command parameters

This commit is contained in:
yzhh 2023-05-23 00:05:59 +08:00
parent 96d5a1bd66
commit ba9aa2e053
3 changed files with 39 additions and 13 deletions

View file

@ -1,10 +1,12 @@
import re
import traceback
import inspect
from datetime import datetime
from aiocqhttp.exceptions import ActionFailed
from config import Config
from core.types import MessageSession as MessageSession_T
from core.builtins import command_prefix, ExecutionLockList, ErrorMessage, MessageSession, MessageTaskManager, Url
from core.exceptions import AbuseWarning, FinishedException, InvalidCommandFormatError, InvalidHelpDocTypeError, \
WaitCancelException, NoReportException
@ -236,11 +238,38 @@ async def parser(msg: MessageSession, require_enable_modules: bool = True, prefi
msg.target.targetFrom not in submodule.available_for):
raise InvalidCommandFormatError
kwargs = {}
func_params = inspect.signature(submodule.function).parameters
if len(func_params) > 1:
for param_name, param_obj in func_params.items():
if isinstance(param_obj.annotation, MessageSession_T.__class__):
kwargs[param_name] = msg
param_name_ = param_name
if (param_name__ := f'<{param_name}>') in msg.parsed_msg:
param_name_ = param_name__
if param_name_ in msg.parsed_msg:
kwargs[param_name] = msg.parsed_msg[param_name_]
try:
if param_obj.annotation == int:
kwargs[param_name] = int(msg.parsed_msg[param_name_])
elif param_obj.annotation == float:
kwargs[param_name] = float(msg.parsed_msg[param_name_])
elif param_obj.annotation == bool:
kwargs[param_name] = bool(msg.parsed_msg[param_name_])
except KeyError:
raise InvalidCommandFormatError
else:
if param_name_ not in kwargs:
kwargs[param_name_] = None
else:
kwargs[func_params[list(func_params.keys())[0]].name] = msg
if not senderInfo.query.disable_typing:
async with msg.Typing(msg):
await parsed_msg[0].function(msg) # 将msg传入下游模块
await parsed_msg[0].function(**kwargs) # 将msg传入下游模块
else:
await parsed_msg[0].function(msg)
await parsed_msg[0].function(**kwargs)
raise FinishedException(msg.sent) # if not using msg.finish
except InvalidCommandFormatError:
await msg.sendMessage(msg.locale.t("parser.command.format.invalid",

View file

@ -18,12 +18,10 @@ async def _(msg: MessageSession):
@coin.command('[<amount>] {{coin.help}}')
async def _(msg: MessageSession):
amount = msg.parsed_msg.get('<amount>', '1')
if not amount.isdigit():
await msg.finish(msg.locale.t('coin.message.error.amount') + amount)
else:
await msg.finish(await flipCoins(int(amount), msg))
async def _(msg: MessageSession, amount: int):
if not amount:
amount = 1
await msg.finish(await flipCoins(int(amount), msg))
@coin.regex(r"[丢|抛]([^个|個|枚]*)?[个|個|枚]?硬[币|幣]", desc='{coin.help.regex.desc}')

View file

@ -17,18 +17,17 @@ phi = module('phigros', developers=['OasisAkari'], desc='{phigros.help.desc}',
@phi.command('bind <sessiontoken> {{phigros.help.bind}}')
async def _(msg: Bot.MessageSession):
async def _(msg: Bot.MessageSession, sessiontoken: str):
need_revoke = False
send_msg = []
if msg.target.targetFrom in ['QQ|Group', 'QQ|Guild', 'Discord|Channel', 'Telegram|group', 'Telegram|supergroup']:
send_msg.append(await msg.sendMessage(msg.locale.t("phigros.message.bind.warning")))
need_revoke = True
token: str = msg.parsed_msg['<sessiontoken>']
headers = p_headers.copy()
headers['X-LC-Session'] = token
headers['X-LC-Session'] = sessiontoken
get_user_info = await get_url('https://phigrosserver.pigeongames.cn/1.1/users/me', headers=headers, fmt='json')
if 'nickname' in get_user_info:
bind = PgrBindInfoManager(msg).set_bind_info(sessiontoken=token, username=get_user_info['nickname'])
bind = PgrBindInfoManager(msg).set_bind_info(sessiontoken=sessiontoken, username=get_user_info['nickname'])
if bind:
send_msg.append(await msg.sendMessage(msg.locale.t("phigros.message.bind.success",
username=get_user_info['nickname'])))
@ -46,7 +45,7 @@ async def _(msg: Bot.MessageSession):
@phi.command('b19 {{phigros.help.b19}}')
async def _(msg: Bot.MessageSession):
if bind := PgrBindInfoManager(msg).get_bind_info() is None:
if (bind := PgrBindInfoManager(msg).get_bind_info()) is None:
await msg.finish(msg.locale.t("phigros.message.user_unbound", prefix=msg.prefixes[0]))
else:
try: