我有一个命令vote
,它将接受2个子命令start
或end
。想法是,如果未指定,它将使用我可以设置的默认值。否则,它将使用函数start
和end
对其进行解析。
例如,进行$vote new start 5m
将使用默认的结束时间,并分析开始时间。
执行$vote new end 5m
将使用默认的开始时间并解析结束时间。
执行$vote new start 5m end 10m
会同时解析开始时间和结束时间。
@vote.group(pass_context=True, invoke_without_command=True)
async def new(ctx):
log.debug('New')
# Do logic for default values here
@new.command()
async def start(ctx, start_time):
# Parse start time
delta = convert_to_timedelta(start_time)
vote_date = datetime.today() + delta
@new.command()
async def end(ctx, end_time):
# Parse end time
delta = convert_to_timedelta(end_time)
但是有没有适当的方法来链接此链接?我当前的解决方案仅使用1条命令new
,并且使用诸如if 'start' in args
之类的参数来解析参数。
这是最好的方法吗,还是有一种更适当的方法来链接可选子命令?
答案 0 :(得分:1)
以下内容假设convert_to_timedelta
如果失败将引发某种异常。在这里,我们定义了两个转换器类,分别确定一个单词是开始还是结束。使用这些,我们可以将所有逻辑整合到一个命令中:
from discord.ext.commands import Converter, BadArgument
from typing import Optional
class IsStart(Converter):
async def convert(self, ctx, argument):
if argument.lower() == 'start':
return argument
raise BadArgument(argument)
class IsEnd(Converter):
async def convert(self, ctx, argument):
if argument.lower() == 'end':
return argument
raise BadArgument(argument)
@bot.command()
async def comm(ctx, start: Optional[IsStart], starttime: Optional[convert_to_timedelta],
end: Optional[IsEnd], endtime: Optional[convert_to_timedelta]):
print(start, starttime, end, endtime)
starttime = starttime if start else 'default_start'
endtime = endtime if end else 'default_end'
await ctx.send(f'{starttime} {endtime}')