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

基于discord.py的多服务器Discord机器人独立冷却系统开发咨询

实现Discord多服务器独立命令冷却(discord.py)

要实现用户在不同服务器的命令冷却相互独立,核心是让冷却的作用范围限定为「用户+服务器」的组合,而非默认的全局用户冷却。以下是具体实现方案:

1. 自定义冷却标识Key

discord.py的冷却系统支持通过key参数自定义冷却的唯一标识,我们返回用户ID和服务器ID的元组,确保每个用户在不同服务器的冷却互不干扰:

def guild_user_cooldown_key(ctx):
    return (ctx.author.id, ctx.guild.id)

2. 为普通前缀命令添加独立冷却

在命令装饰器中指定自定义冷却key,同时设置冷却次数和时长:

from discord.ext import commands
import discord

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
# 1分钟内每个用户在单服务器只能调用1次,使用自定义冷却标识
@commands.cooldown(1, 60, commands.BucketType.user, key=guild_user_cooldown_key)
async def hello(ctx):
    await ctx.send(f"你好 {ctx.author.mention}!")

3. 处理冷却触发提示

通过on_command_error事件捕获冷却错误,给用户发送针对性提示:

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        remaining_time = round(error.retry_after, 2)
        await ctx.send(f"当前服务器该命令还在冷却中,请等待{remaining_time}秒后重试!")
    # 保留其他错误的默认处理(可选)
    else:
        raise error

4. 斜杠命令的实现方式(discord.py 2.0+)

如果使用斜杠命令,同样可以通过自定义key实现独立冷却:

from discord import app_commands

@app_commands.checks.cooldown(1, 60, key=lambda interaction: (interaction.user.id, interaction.guild.id))
@app_commands.command(name="hello_slash")
async def hello_slash(interaction: discord.Interaction):
    await interaction.response.send_message(f"你好 {interaction.user.mention}!")

# 同步斜杠命令到服务器
@bot.event
async def on_ready():
    await bot.tree.sync()
    print(f"已登录为 {bot.user}")

关键说明

  • 自定义key函数返回的元组会作为冷却桶的唯一标识,确保用户在A服务器的冷却不会影响其在B服务器的命令使用
  • 冷却参数中的1, 60可按需调整,分别代表「允许调用次数」和「冷却时长(秒)」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:55:18