如何重置Discord斜杠命令冷却?解决错频道及命令错误场景问题
解决方案
要实现错误频道使用命令、命令执行出错时重置冷却,核心是获取命令的冷却器实例,通过对应key重置冷却。以下是修改后的代码及关键说明:
关键修改点
- 错误频道时重置冷却:在引导用户前往正确频道后,获取当前命令的冷却器,计算对应key并调用
reset() - 命令出错时重置冷却:在全局错误处理中,针对非冷却类错误,尝试重置触发错误的命令的冷却
修改后的完整代码
import discord from discord import app_commands import datetime @client.tree.command(name="command", description="xxxxx") @app_commands.checks.cooldown(1, 3600, key=lambda i: (i.channel_id,i.user.id)) async def command(interaction: discord.Interaction): if interaction.channel.id != 1145817930429378661: embed = discord.Embed(colour=0xe5ff00, timestamp=datetime.datetime.now(), description=f"Please use <#1145817930429378661> for this command!") embed.set_footer(text="xxx",icon_url="xxx.png") await interaction.response.send_message(embed=embed,ephemeral=True) # 重置当前用户在该频道的冷却 cooldown = command._cooldown key = cooldown.key(interaction) cooldown.reset(key) return try: user = interaction.user.name except: user = "[ Unable to get name ]" print(f"{user} ran /command") @client.tree.error async def on_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CommandOnCooldown): cooldown = round(error.retry_after/60) time = "minutes" if cooldown > 60: cooldown = round(cooldown / 60) time = "hours" await interaction.response.send_message(f"You are currently on cooldown, you can reuse this command in {cooldown} {time}!",ephemeral=True) else: print(error) # 尝试重置冷却 try: cmd = interaction.command if cmd and hasattr(cmd, '_cooldown'): cooldown = cmd._cooldown key = cooldown.key(interaction) cooldown.reset(key) except Exception as e: print(f"重置冷却失败: {e}") await interaction.response.send_message("There was an error, please retry the command! :slight_smile:",ephemeral=True)
注意事项
- 冷却器的
_cooldown是discord.py的内部属性,但目前稳定可用,若后续版本有变动需注意官方文档更新 - 计算key时必须和装饰器中
key参数的逻辑保持一致,这里直接调用cooldown.key(interaction)自动生成,避免手动拼接出错 - 错误处理中的重置操作包裹在
try-except中,防止重置过程中出现新错误,影响错误提示消息的发送
内容的提问来源于stack exchange,提问作者m_cr
相关产品推荐
相关产品推荐

