Discord.py如何检查Slash Command是否存在?禁用命令功能异常求助
解决Discord.py中Slash命令存在性检查的问题
你的问题根源在于直接用字符串和Command对象实例做匹配——tree.get_commands()返回的是discord.app_commands.Command对象的列表,而非命令名字符串,因此command in ...的判断永远无法命中。
修复代码
你需要提取每个命令对象的name属性来完成比对,同时注意移除命令时需指定服务器(因为你的命令是服务器专属的):
@tree.command(guild=discord.Object(id=1129737425653071992), name='disable', description='Disable a specified Command') async def disable(interaction: discord.Interaction, command: str): guild = discord.Object(id=1129737425653071992) # 获取当前服务器所有命令,并提取命令名集合 existing_commands = tree.get_commands(guild=guild) command_names = {cmd.name for cmd in existing_commands} if command in command_names: # 移除服务器专属命令必须指定guild参数 await tree.remove_command(command, guild=guild) await interaction.response.send_message(f"{command} 已禁用。可使用 /enable {command} 重新启用") else: await interaction.response.send_message(f"未找到命令:{command}")
核心要点
- 命令名提取:遍历
get_commands()返回的Command对象,取出每个对象的name属性存入集合(集合的查找效率比列表更高)。 - 服务器参数必填:由于你的
disable命令是绑定到特定服务器的,移除目标命令时必须传入guild参数,否则Discord.py会默认查找全局命令,导致操作失效。
内容的提问来源于stack exchange,提问作者DZultra
相关产品推荐
相关产品推荐

