You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为discord.py中的斜杠命令设置5小时冷却时间?

在discord.py中为斜杠命令设置5小时冷却时间

要给你的斜杠命令添加5小时冷却限制,需要使用discord.py的app_commands.checks.cooldown装饰器,并配套处理冷却触发时的错误提示。以下是具体实现步骤和修改后的完整代码:

实现步骤

  • 导入discord.app_commands模块中的checks工具
  • 在命令函数上方添加冷却装饰器,指定冷却规则
  • 为命令添加错误处理函数,捕获冷却触发异常并提示用户

修改后的完整代码

from discord import Interaction, SyncWebhook
from discord.app_commands import Group, checks
import math

# 假设你的slashDev是已定义的命令组
# slashDev = Group(name="slashdev", description="开发者相关命令")

@slashDev.command(name='requestfeature', description='Requests feature to the bot devs')
@checks.cooldown(1, 18000, key=lambda interaction: interaction.user.id)  # 1次/18000秒(5小时),按用户ID限制
async def requestfeature(interaction: Interaction, msg : str):
    # 修正原代码中webhook URL的引号缺失问题
    webhook = SyncWebhook.from_url("https://discord.com/api/webhooks/donttryme")
    webhook.send(f"`request: {msg} from {interaction.user}`")
    await interaction.response.send_message('**Thanks for requesting a feature**', ephemeral=True)

# 为命令添加冷却错误处理
@requestfeature.error
async def requestfeature_error(interaction: Interaction, error):
    if isinstance(error, checks.CommandOnCooldown):
        # 计算剩余时间并格式化
        hours = math.floor(error.retry_after / 3600)
        minutes = math.floor((error.retry_after % 3600) / 60)
        seconds = math.floor(error.retry_after % 60)
        await interaction.response.send_message(
            f"该命令冷却中,请等待{hours}小时{minutes}分钟{seconds}秒后再尝试。",
            ephemeral=True
        )
    else:
        # 处理其他错误
        await interaction.response.send_message("命令执行出错,请稍后重试。", ephemeral=True)

代码说明

  • @checks.cooldown(1, 18000, key=lambda interaction: interaction.user.id):
    • 第一个参数1表示每冷却周期内允许执行1次
    • 第二个参数18000是冷却时间(单位:秒),5小时=5×3600=18000秒
    • key参数指定以用户ID作为冷却的唯一标识,确保每个用户独立触发冷却,互不影响
  • 错误处理函数requestfeature_error:捕获CommandOnCooldown异常,将剩余冷却时间转换成易读的时分秒格式,告知用户

内容的提问来源于stack exchange,提问作者aadrian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:26:12