Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - How to use command name with spaces?

How to make bot works when there is a space between commands in python bot. I know we can do that using sub-command or on_message but is there any another option to do that for only selected commands not for all commands.

The following code will not work.

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

So I tried using alias but still it won't working.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strictly to say, you can't. Since discord.py's command names ends with space, as defined in views.py. There are, however, a few options: re write how discord.py views handle messages (I wouldn't recommend this), use on_message and message.content.startswith, or use groups.

Since on_message is fairly straight forward to use, I will instead show you how you can "hack" the group syntax to allow command name with spaces.

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)

In discord:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...