如何为discord.py hybrid命令添加冷却?遇属性错误求助
问题原因与解决方法
核心问题
你只处理了前缀命令的冷却错误,但混合命令以斜杠命令触发时,抛出的是app_commands.CommandOnCooldown错误,而非commands.CommandOnCooldown;同时on_command_error仅能捕获前缀命令的错误,斜杠命令的错误需要单独处理,这就是机器人无响应且报错的原因。
具体修复步骤
1. 新增斜杠命令错误处理器
给bot.tree注册专属错误处理函数,捕获斜杠命令触发的冷却错误:
@bot.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(f"你处于冷却中,请{round(error.retry_after)}秒后再试", ephemeral=True)
2. 保留前缀命令错误处理
原有的on_command_error可以继续保留,处理前缀触发的冷却情况:
async def on_command_error(self, ctx, error): if isinstance(error, commands.CommandOnCooldown): await ctx.send(f"你处于冷却中,请{round(error.retry_after)}秒后再试")
3. 完整修正代码
import discord from discord.ext import commands from discord import app_commands guild_id = 你的服务器ID # 替换为实际服务器ID class Bot(commands.Bot): def __init__(self): intents = discord.Intents.all() intents.message_content = True super().__init__(command_prefix = "!", case_insensitive = True,intents = intents, activity=discord.Activity(type=discord.ActivityType.listening, name='/info')) async def setup_hook(self): await self.tree.sync() await self.tree.sync(guild = discord.Object(id = guild_id)) print(f"Synced slash commands for {self.user}") async def on_command_error(self, ctx, error): if isinstance(error, commands.CommandOnCooldown): await ctx.send(f"你处于冷却中,请{round(error.retry_after)}秒后再试") bot = Bot() # 处理斜杠命令错误 @bot.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): await interaction.response.send_message(f"你处于冷却中,请{round(error.retry_after)}秒后再试", ephemeral=True) @bot.hybrid_command(name = "command", with_app_command = True, description = "This is a test command") @commands.cooldown(1, 30, commands.BucketType.user) async def command(ctx: commands.Context): await ctx.send("命令执行成功!") # 补充命令逻辑 bot.run("你的Bot令牌")
额外说明
@commands.cooldown装饰器对混合命令的两种触发方式均生效,但错误类型不同,必须分开处理。ephemeral=True可让冷却提示仅触发者可见,避免频道刷屏。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

