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

Python Discord bot实现自定义命令冷却及IndentationError报错解决

Discord.py 自定义命令冷却问题修复方案

报错原因

  1. 语法层面:@commands.cooldown装饰器错误放置在函数体内部,缩进不符合Python规范,直接触发了IndentationError。
  2. 逻辑层面:默认的commands.cooldown是静态装饰器,仅在函数定义阶段读取参数固定冷却时长,无法获取运行时用户传入的time值,即使修正缩进也无法实现自定义冷却的需求。

实现方案

放弃静态冷却装饰器,改用运行时动态设置冷却的逻辑:每次用户调用命令先检查是否在冷却期,未冷却则拦截请求,冷却已结束则执行业务逻辑,执行完成后根据用户传入的时长为该用户设置对应长度的冷却。

修复后代码

import discord
from discord.ext import commands
import requests

# 此处替换为你自己的bot前缀和intents配置
client = commands.Bot(command_prefix="!", intents=discord.Intents.default())

@client.command()
async def text(ctx, ip, port, time: int, method):
    # 冷却检查逻辑
    if ctx.command.cooldown:
        bucket = ctx.command.get_cooldown_context(ctx)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            await ctx.send(f"命令冷却中,还需等待{round(retry_after, 1)}秒")
            return
    
    # 原有业务逻辑
    url = f'N/A'
    response = requests.get(url)
    embed = discord.Embed()

    embed.title = 'Launched'
    print(f'{ip}')
    print(f'{port}')
    print(f'{time}')        
    print(f'{method}')
    embed.add_field(name = 'IP', value = ip, inline=False)
    embed.add_field(name = 'PORT', value = port, inline=False)
    embed.add_field(name = 'TIME', value = f'{time}', inline=False)
    embed.add_field(name = 'METHOD', value = method, inline=False)
    print(ctx.author, 'in', ctx.guild)

    embed.set_author(name="Proll's Bot", icon_url=client.user.avatar_url)
    await ctx.send(embed = embed)

    # 动态设置用户侧冷却,时长为用户传入的time值
    ctx.command.cooldown = commands.Cooldown(1, time, commands.BucketType.user)

注意事项

  • 给time参数添加了int类型标注,discord.py会自动将用户传入的字符串参数转为整数,避免类型不匹配报错。
  • 冷却粒度为用户级别(commands.BucketType.user),不同用户的冷却时间互不影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 02:54:04