discord.py斜杠命令可重置服务器冷却功能故障排查求助
问题原因
你代码里的核心问题是每次调用get_ratelimit都会新建一个CooldownMapping实例,导致冷却状态无法在多次调用间保存,所以每次update_rate_limit都会返回None,相当于没有冷却限制。
修复方案
把CooldownMapping作为类的实例属性初始化,确保冷却状态可以持久化,同时添加重置冷却的方法:
import typing from discord import app_commands from discord.ext import commands # 假设这是你的Cog类 class YourCog(commands.Cog): def __init__(self, bot): self.bot = bot # 初始化冷却映射:每服务器20秒1次 self.guild_cooldown = commands.CooldownMapping.from_cooldown( 1, 20, commands.BucketType.guild ) def get_ratelimit(self, inter) -> typing.Optional[float]: # 使用类实例的冷却映射,而不是每次新建 bucket = self.guild_cooldown.get_bucket(inter) return bucket.update_rate_limit() def reset_guild_cooldown(self, guild_id: int): # 重置指定服务器的冷却 if guild_id in self.guild_cooldown._cache: del self.guild_cooldown._cache[guild_id] @app_commands.command(name="cooldown_test", description="Testing cooldown") async def cooldown_test(self, inter): limit = self.get_ratelimit(inter) if limit is None: # 冷却已重置/未触发,执行命令逻辑 await inter.response.send_message("命令执行成功!", ephemeral=True) # 示例:满足某个条件时重置冷却(比如这里假设条件为True) some_condition = True if some_condition: self.reset_guild_cooldown(inter.guild.id) await inter.followup.send("冷却已重置!", ephemeral=True) else: # 冷却中,提示剩余时间 await inter.response.send_message( f"命令正在冷却中,请等待{round(limit, 1)}秒后重试。", ephemeral=True )
关键改动说明
- 持久化冷却映射:把
CooldownMapping放在类的__init__里初始化,确保所有命令调用共享同一个冷却状态存储。 - 正确获取冷却桶:使用实例属性
self.guild_cooldown获取对应服务器的冷却桶,而不是每次新建。 - 重置冷却逻辑:通过直接删除
_cache中对应服务器的条目来重置冷却,这样下次调用时会重新计算冷却时间。 - 返回值处理:
update_rate_limit()返回的是剩余冷却时间(浮点数),冷却结束时返回None,注意用is None而不是== None更规范。
内容的提问来源于stack exchange,提问作者rxnen
相关产品推荐
相关产品推荐

