python - Discord.py 重写冷却命令

标签 python python-3.x discord discord.py

我正在使用 Discord.py Rewrite 来制作 Discord 机器人。我有一个名为 work 的命令,其中包含以下代码:

import discord
from discord.ext import commands

client = commands.Bot(command_prefix="c!")
# on_ready command

@client.command()
async def work(ctx):
    author_id = ctx.author.id
    currency_dict[author_id] += 50
    await ctx.send("You Gained 50 Coins")
# currency_dict is a dictionary that is already defined

有没有办法让用户每30秒只能使用一次该命令?谢谢!

最佳答案

首先,您必须导入from discord.ext.commands.cooldowns import BucketType。这将帮助你冷却。下面是可用于此导入的 cooldown 检查以及 max_concurrency 检查。

from discord.ext.commands.cooldowns import BucketType
# BucketType can be BucketType.default, member, user, guild, role, or channel
@commands.cooldown(rate,per,BucketType) 
# Limit how often a command can be used, (num per, seconds, BucketType)

@commands.max_concurrency(number, per=BucketType.default, *, wait=False)
# Limit how many instances of the command can be running at the same time.
# Setting wait=True will queue up additional commands. False will raise MaxConcurrencyReached

# Checks can be stacked, and will Raise a CheckFailure if any check fails.

就您而言,您需要使用commands.cooldown(rate,per,BucketType)

import discord
from discord.ext import commands
from discord.ext.commands.cooldowns import BucketType

client = commands.Bot(command_prefix="c!")
# on_ready command

@client.command()
@commands.cooldown(1,30,commands.BucketType.user) # one command, every 30 seconds, per user
async def work(ctx):
    author_id = ctx.author.id
    currency_dict[author_id] += 50
    await ctx.send("You Gained 50 Coins")
# currency_dict is a dictionary that is already defined

# cooldown error-handling
@work.error
async def work_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'This command is on cooldown, you can use it in {round(error.retry_after, 2)} seconds')


引用文献:

关于python - Discord.py 重写冷却命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65375528/

相关文章:

python - 将带有空格字符的参数传递到 argparse

python - 如何在 python 3 中将二进制数据写入标准输出?

javascript - Discord.js 类型错误 : Cannot read property 'name' of undefined

python - 统计模型多元方差分析 : IndexError: index 1 is out of bounds for axis 0 with size 1

python - ipython 笔记本的 matplotlib 和 libpng 问题

python - 属性错误: '_mysql.connection' object has no attribute 'cursor'

javascript - Discord.js : member. guild.channels.find 不是函数

python - Discord python bot on_message return 语句中断命令

Windows 10 for Linux环境下的Python编程

Python 3,如何用打印清除行以进行覆盖?