[英]How to make a cooldown system with discord.py?
假設我有兩個命令......
hi 1
向用戶發送 hi 一次並開始 500 秒的冷卻時間hi 2
向用戶發送 hi 兩次並開始 1000 秒的冷卻時間現在,當我輸入hi 1
時,它不應該在我輸入hi 2
時響應我。 類似於共享冷卻系統的東西!
我怎樣才能做到這一點?
我目前正在使用這個:
@commands.cooldown(1, 5, commands.BucketType.user)
這使我可以使用多個命令,而無需停止前一個命令的冷卻時間。
您可以使用自定義檢查來確保命令在冷卻時不被使用。 ./q63262849/cooldowns.py
import datetime
from discord.ext import commands
on_cooldown = {} # A dictionary mapping user IDs to cooldown ends
def cooldown(seconds):
def predicate(context):
if (cooldown_end := on_cooldown.get(context.author.id)) is None or cooldown_end < datetime.datetime.now(): # If there's no cooldown or it's over
if context.valid and context.invoked_with in (*context.command.aliases, context.command.name): # If the command is being run as itself (not by help, which runs checks and would end up creating more cooldowns if this didn't exist)
on_cooldown[context.author.id] = datetime.datetime.now() + datetime.timedelta(seconds=seconds) # Add the datetime of the cooldown's end to the dictionary
return True # And allow the command to run
else:
raise commands.CommandOnCooldown(commands.BucketType.user, (cooldown_end - datetime.datetime.now()).seconds) # Otherwise, raise the cooldown error to say the command is on cooldown
return commands.check(predicate)
然后可以導入
./main.py
from q63262849 import cooldowns
並用作命令的裝飾器
./main.py
@bot.command()
@cooldowns.cooldown(10)
async def cooldown1(ctx):
await ctx.send("Ran cooldown 1")
@bot.command()
@cooldowns.cooldown(20)
async def cooldown2(ctx):
await ctx.send("Ran cooldown 2")
值得注意的是,這種方法仍然存在一些問題,特別是如果稍后的另一個檢查失敗,此檢查仍會將命令置於冷卻狀態,但是可以通過放置此檢查以使其在所有其他檢查之后運行來解決這些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.