【问题标题】:Multiple word command in discord.py (commands extension)discord.py 中的多字命令(命令扩展)
【发布时间】:2021-05-23 16:00:05
【问题描述】:

我正在为我的 Discord 机器人使用 discord.ext.commands 模块,并且 我想要一个名为“设置前缀”的多字命令。

当我使用该命令时,它会引发 CommandNotFound 错误,表明“设置”不是命令。 所以看起来 discord.py 只检查第一个单词。

有没有办法解决这个问题?

这是我的代码的 sn-p:

@commands.command(name="setup prefix")
async def set_prefix(self, ctx: Context, prefix: str):
    pass

是的,我知道,我可以将“前缀”作为附加参数。但是我必须使用一个函数来完成所有设置命令。

感谢您的帮助:)

【问题讨论】:

  • 出于安全原因,我怀疑这是消息解析中内置的内容。为什么不让setup 处理程序根据下一个参数调用哪个其他函数。您可以让它根据参数动态调用其他函数。设置函数可以运行getattr(self, f"handle_setup_{arg}")(ctx)

标签: python discord command discord.py


【解决方案1】:

您可能想要使用命令组


@commands.group(invoke_without_subcommand=True)
async def setup(self, ctx, *args):
    # general functionality, help, or whatever.
    pass

@setup.command()
async def prefix(self, ctx, prefix):
    #logic
    pass

请查看文档以获取更多信息和示例

https://discordpy.readthedocs.io/en/latest/ext/commands/api.html?highlight=commands%20group#discord.ext.commands.group

另请阅读库常见问题解答,其中包含此用例的一些示例。 https://discordpy.readthedocs.io/en/latest/faq.html

注意:请原谅我在手机上的丑陋链接,当我到达计算机时,我会将它们作为参考进行编辑

【讨论】:

  • 感谢您的快速回答!一分钟前也找到了群组。这正是我搜索的内容。
【解决方案2】:

只是将我的评论写成提案。我认为您不能创建多名称命令。可能是设计使然,因为我认为这会带来安全风险并增加大量处理。在后端,每条消息都必须事先知道命令有多少部分。

我建议你这样做

是的,我知道,我可以将“前缀”作为附加参数。

但不是

但是我必须使用一个函数来执行所有设置命令。

应该是这样的:

# all of this is in the same class whatever that's called. 

async def handle_setup_giraffe(self, ctx: Context):
    pass

@commands.command(name="setup")
async def setup(self, ctx: Context):
    setup_command = ctx.args[0]
    if hasattr(self, f"handle_setup_{setup_command}"):
        return getattr(self, f"handle_setup_{setup_command}")(ctx)
    else:
        raise SomeException("Setup command not found", setup_command)

【讨论】:

  • 感谢您的帮助!事实上,其他人已经提到的群组正是我搜索的内容。
猜你喜欢
  • 2021-03-26
  • 1970-01-01
  • 2020-09-27
  • 2016-09-07
  • 2015-12-19
  • 2019-08-11
  • 2021-08-28
  • 2021-01-22
  • 2021-03-30
相关资源
最近更新 更多