首页 > 解决方案 > 如何使用带空格的命令名称?

问题描述

python bot中的命令之间有空格时如何使bot工作。我知道我们可以使用子命令on_message来做到这一点,或者还有其他选项可以仅针对选定的命令而不是所有命令来执行此操作。

以下代码将不起作用。

@bot.command(pass_context=True)
async def mobile phones(ctx):
    msg = "Pong. {0.author.mention}".format(ctx.message)
    await bot.say(msg)

所以我尝试使用别名,但它仍然无法正常工作。

@bot.command(pass_context=True, aliases=['mobile phones'])
async def phones(ctx):
    msg = "Pong. {0.author.mention}".format(ctx.message)
    await bot.say(msg)

标签: pythondiscorddiscord.py

解决方案


严格来说,你不能。由于 discord.py 的命令名称以空格结尾,如 views.py 中所定义。但是,有几个选项:重新编写 discord.py 视图如何处理消息(我不推荐这样做)、使用on_messageandmessage.content.startswith或使用组。

由于on_message使用起来相当简单,我将向您展示如何“破解”group语法以允许命令名称带有空格。

class chain_command:
    def __init__(self, name, **kwargs):
        names = name.split()
        self.last = names[-1]
        self.names = iter(names[:-1])
        self.kwargs = kwargs

    @staticmethod
    async def null():
        return

    def __call__(self, func):
        from functools import reduce
        return reduce(lambda x, y: x.group(y)(self.null), self.names, bot.group(next(self.names))(self.null)).command(self.last, **self.kwargs)(func)

@chain_command("mobile phones", pass_context=True)
async def mobile_phones(ctx):
    msg = "Pong. {0.author.mention}".format(ctx.message)
    await bot.say(msg)

不和谐:

me: <prefix>mobile phones
bot: Pong. @me

推荐阅读