python - 程序 Discord.py 命令使用消息
问题描述
我正在将错误消息实现到我的Discord.py
机器人中,在那里我使用 cogs 来实现命令。
当用户错误地使用命令时,例如没有将参数传递给需要它们的命令,我希望机器人通知他们该特定命令的正确用法。
例如,这里我有一个简单的 cog test.py
;
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def test_command(self, ctx, arg1: str, arg2: int):
msg = f"{arg1} and {arg2 + 5}"
await ctx.reply(msg)
def setup(client):
client.add_cog(Test(client))
如果用户错误地使用了命令,例如 types !test_command foo
,我希望机器人返回一条消息,如下所示
正确用法:!test_command <arg1> <arg2>
我该怎么做呢?我想按程序进行,而不必从每个命令的预先编写的使用帮助消息列表中进行选择。
提前致谢。
编辑:请注意我已经有了错误检查逻辑。我在问 - 在错误触发的情况下 - 如何自动生成一条消息以通知用户如何使用该命令。
解决方案
您正在寻找Command.signature。这将自动为您提供命令的用法。只需将它与on_command_error
和MissingRequiredArgument
错误结合使用即可。
例子:
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Correct Usage: {ctx.prefix}{ctx.command.name} {ctx.command.signature}")
这将返回Correct Usage: !test_command <arg1> <arg2>
推荐阅读
- android - Glide,可以获得图像文件大小(不是尺寸)吗?
- mysql - MySQL用子分区重新组织分区
- opencv - 如何计算每个通道值的 RGB 图像标准偏差
- python - Django不导入CSS
- javascript - React - 未使用回调中设置的道具表达式重新渲染的子组件数组
- python - 项目 Euler #12 - 两种代码的性能差异
- python - 如何基于计时器迭代数据帧?
- javascript - 单击链接或导航外部时如何关闭导航?
- asp.net - HttpClient.SendAsync exeption:底层连接已关闭:连接意外关闭
- java - 在 SQL 查询中转义换行符