为交互按钮设置冷却时间



我想给我的交互按钮添加一个冷却功能。

这是我的基本代码。

import discord
from discord.ext import commands

class CookieButton(discord.ui.Button):
def __init__(self):
super().__init__(style=discord.ButtonStyle.primary, label="🍪", custom_id="cookie", row=0)

@commands.cooldown(1, 5, commands.BucketType.user) # this doesn't work but want to make it work samely. (5 second cooldown)
async def callback(self, interaction: discord.Interaction):
view: CookieView = self.view
view.cookie += 1
await interaction.response.edit_message(content=f"You have {view.cookie} cookie(s) 🍪.", view=view)

class CookieView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(CookieButton())
self.cookie = 0

bot = commands.Bot(command_prefix="!")
@bot.command(name="cookie")
async def _cookie(ctx: commands.Context):
view: CookieView = CookieView()
await ctx.send("You have 0 cookie 🍪.", view=view)
bot.run("token")

在这篇文章中,我想让每个用户每5秒执行一次回调函数。

我怎样才能使它按我的意图工作?

您可以使用创建自定义冷却时间

cd_mapping = commands.CooldownMapping.from_cooldown(10, 10, commands.BucketType.member)
class CookieView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(CookieButton())
self.cookie = 0
self.cd_mapping = commands.CooldownMapping.from_cooldown(10, 10, commands.BucketType.member)

然后在您的callback功能中检查会员是否有费率限制:

async def callback(self, interaction: discord.Interaction):
view: CookieView = self.view
bucket = view.cd_mapping.get_bucket(interaction.message)
retry_after = bucket.update_rate_limit()
if retry_after:
return await interaction.response.send_message("Sorry, you are rate limited.", ephemeral=True)
view.cookie += 1
await interaction.response.edit_message(content=f"You have {view.cookie} cookie(s) 🍪.", view=view)

您可以尝试保存用户临时按下按钮的情况(如阻止列表(,当用户按下按钮时,您可以将用户id与列表中的id进行比较。您可以在用户上次按下按钮时制作一个字典,并将其与新的时间戳进行比较。要使按钮工作,如果您的用户在列表中,您可以立即删除对不和消息的反应。

最新更新