第一件小事,tree.remove_command(command)
就是not.
无论如何,你真正想做的是禁用命令无论如何,
How to create a disable command in discord.py
判断是否存在
tree.get_commands
个退货:
List[Union[ContextMenu, Command, Group]]
这意味着,如果你想具体判断Command
,你必须解析它.command
参数也是一个字符串,这就是为什么它最初没有返回true的原因.但是,我们可以在命令树中使用一个更简单的命令.
应该怎么做
tree.get_command
(单数不复数)返回:
Optional[Union[Command, ContextMenu, Group]]
是的,这是一回事.但是,参数是不同的.
命令(Str)-要获取的根命令的名称.
行会(可选[snowflake])-要获得命令的行会.如果未给出或无,则它将获得一个全局命令.
type(AppCommandType)—要获取的命令类型.切换到chat_input,即斜杠命令.
您可以将之前的command
字符串参数传入此命令.然后你可以判断它是否返回任何东西.这比解析快得多(如前所述).您也不会判断是否存在多个命令,因此这是最佳 Select .
下面我有一个代码示例(作为参考,我之前做了另一个命令):
@tree.command(guild=discord.Object(id=guild_id), name='disable', description='Disable a specified Command')
async def disable(interaction: discord.Interaction, command: str):
if tree.get_command(command, guild=discord.Object(id=guild_id)):
tree.remove_command(command, guild=discord.Object(id=guild_id)) # remove the command
await interaction.response.send_message(
f"{command} was disabled. You can reenable it by running /enable {command}")
else:
await interaction.response.send_message(f"Command could not be found: {command}")
禁用命令
但是,这实际上并不会禁用该命令.这是为什么?如果是tree.remove_command
,则需要同步树.只需添加一行:
await tree.sync(guild=discord.Object(id=guild_id))
它应该会奏效的!
完整代码:
@tree.command(guild=discord.Object(id=guild_id), name='disable', description='Disable a specified Command')
async def disable(interaction: discord.Interaction, command: str):
await interaction.response.defer()
if tree.get_command(command, guild=discord.Object(id=guild_id)): # check if the command exists
tree.remove_command(command, guild=discord.Object(id=guild_id)) # remove the command
print("command removed!")
await tree.sync(guild=discord.Object(id=guild_id)) # sync the tree
print("tree synced!")
await interaction.followup.send(
f"{command} was disabled. You can reenable it by running /enable {command}")
else:
await interaction.followup.send(f"Command could not be found: {command}")
Tested this locally & the slash command say
doesn't appear anymore. It's also gone from integrations: