python - 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')
参考:
推荐阅读
- android - 如何传递类似活动的参数
- nightwatch.js - NightwatchJS 无法从元素列表中找到第二个元素
- php - 带有 array_walk_recursive 的 PHP SimpleXMLElement 正在反转键和值
- json - 如何使用地图
在 Flutter 中输入 json - dax - DAX - IsSubTotal - 似乎工作不正常?
- python - Pyinstaller 无法与 Panda3D 一起使用 – 未找到“直接”模块
- java - 由于无法识别的选项,在 Netbeans 11 中运行示例 JavaFX Maven 时出错:--module-path
- javascript - 如何以土耳其语格式返回日期?
- javascript - 尝试计算在 svg 和 javascript 中创建的饼图切片的角度
- php - 如何在 php 中使用图形 api 在 Instagram 上发帖