为 discord.py 添加冷却时间

Adding cooldowns to discord.py

我一直在研究为我的机器人中的特定命令添加冷却时间的方法。我找不到任何有用的东西,而且我不确定如何将 @commands.cooldown(rate=1, per=5, bucket=commands.BucketType.user) 实施到此代码中。

import discord
import random
from pathlib import Path
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType
client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('#help'):
        *command goes here*

    if message.content.startswith('#gamble'):
        *command goes here*

client.run('TOKEN')

我建议您使用 commands.Bot,因为它具有 discord.Client 的所有功能 + 一个完整的命令系统,您重写的代码将如下所示:

import discord
from discord.ext import commands
# You should enable some intents
intents = discord.Intents.default()

bot = commands.Bot(command_prefix="#", intents=intents)
bot.remove_command("help") # Removing the default help command

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

@bot.command()
async def help(ctx): # Commands take a `commands.Context` instance as the first argument
    # ...

@bot.command()
@commands.cooldown(1, 6.0, commands.BucketType.user)
async def gamble(ctx):
    # ...

bot.run("TOKEN")

看看introduction