python - 如何使用带空格的命令名称?
问题描述
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)
解决方案
严格来说,你不能。由于 discord.py 的命令名称以空格结尾,如 views.py 中所定义。但是,有几个选项:重新编写 discord.py 视图如何处理消息(我不推荐这样做)、使用on_message
andmessage.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
推荐阅读
- java - tkinter python程序可以镜像到android应用程序上吗
- python - 修改CustomUser模型的字段顺序
- jquery - 检测音频何时将在 Jquery 中结束
- datetime - Flutter - 将分钟转换为 H:M
- android - 从 .gradle 和 .idea 中删除所有内容是否安全?
- tampermonkey - Tampermonkey 的“存储”选项卡在哪里编辑存储内容?
- ruby - 尝试在 Ruby 中复制移动应用程序 POST 请求,出现 502 网关错误
- c++ - 正在跳过 cin 并且 cin.ignore 不起作用
- javascript - 使用 Javascript 更改类的 CSS 样式
- asp.net-core - 如何使用实体框架核心更新与普通 SQL 更新查询相同的多条记录列表?