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

如何为Discord经济类Bot的$work指令添加15秒调用冷却限制

实现方案

你直接使用discord.py内置的冷却装饰器即可完成需求,无需自行编写计时逻辑,修改步骤如下:


1. 给work指令添加冷却装饰器

在现有@client.command()下方新增冷却装饰器,三个参数分别对应「单周期允许调用次数」「冷却周期/秒」「冷却生效维度(按用户区分,互不影响)」,修改后的work指令代码如下:

@client.command()
@commands.cooldown(1, 15, commands.BucketType.user) # 新增冷却规则
async def work(ctx):
    await open_account(ctx.author)
    user = ctx.author
    users = await get_bank_data()
    earnings = random.randrange(269)

    await ctx.send(f'{ctx.author.mention} Got {earnings} Coins!!')

    users[str(user.id)]["wallet"] += earnings

    with open("mainbank.json",'w') as f:
        json.dump(users,f)

2. 添加冷却触发的错误处理

不添加错误处理的话,用户触发冷却时Bot只会在控制台抛出异常,不会返回提示,你需要添加如下错误监听代码:

@work.error
async def work_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send("休息一下吧,15秒后再尝试")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:18:00