我为我的 discord bot(用 Python 编写)创建了一个帮助命令,如下所示:
@commands.command()
async def help(self, ctx, cmd = None)
if cmd == None
[list of commands in an embed]
elif cmd == example
[info for example command]
真正的东西有很多 elif 语句(每个命令一个)。到目前为止,它一直运行良好,直到 repl.it 认为我是一个糟糕的程序员并给了我这个错误:
[mccabe] Cyclomatic complexity too high: 24 (threshold 15)
我知道这意味着我的代码太复杂了,但我不确定。 help 命令现在根本不运行。我对 python 和 discord api 还是很陌生,所以如果有人能教我一种更好、更优化的帮助命令方式,我将不胜感激。
顺便说一句,上面的代码是在一个带有正确声明和初始化的 cog 中编写的。
答案 0 :(得分:1)
您可以使用子命令
@bot.group()
async def help(ctx):
if ctx.invoked_subcommand is None:
# Send the initial embed
@help.command()
async def command1(ctx):
# Send the help embed for this command
# To invoke
# !help
# -> initial embed
# !help command1
# -> embed for this command
一个更简单的替代方法是简单地将默认帮助命令子类化,看看this示例
答案 1 :(得分:1)
圈复杂度意味着您的函数中有许多分支(if,else)语句。在这种情况下,限制是 15,而您是 24。
对于您的问题,也许您应该考虑拥有一本字典,其中包含链接到他们的帮助的所有命令。它简单可靠。
commands = {
"first_command": "help message",
"second_command": "help message",
...
}
然后在你的代码中你可以这样做:
@commands.command()
async def help(self, ctx, cmd = None)
try:
print(registry[cmd])
except KeyError:
print([cmd for cmd in registry.keys()])
这只是一个例子。如果你知道 Object.您可以使用包含帮助和其他信息的命令对象列表替换注册表。