Dem*_*try 2 python discord discord.py
当 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)
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用别名,但仍然无法正常工作。
@bot.command(pass_context=True, aliases=['mobile phones'])
async def phones(ctx):
msg = "Pong. {0.author.mention}".format(ctx.message)
await bot.say(msg)
Run Code Online (Sandbox Code Playgroud)
严格地说,你不能。由于 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)
Run Code Online (Sandbox Code Playgroud)
不和谐:
me: <prefix>mobile phones
bot: Pong. @me
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6556 次 |
| 最近记录: |