如何防止用户重复点击Discord.py中的按钮?
解决Discord按钮针对特定用户的禁用与冷却问题
针对你的需求,有两种可行方案:
一、限制用户仅能点击一次按钮
通过维护一个已点击用户的ID集合,实现单个用户只能发起一次问卷。用户重复点击时,仅向其发送ephemeral提示,不影响其他用户使用按钮。
修改后的代码如下:
import discord class surveyView(discord.ui.View): def __init__(self): super().__init__(timeout=None) self.value = None # 存储已点击过按钮的用户ID self.clicked_users = set() @discord.ui.button(label="Let's get started!", style=discord.ButtonStyle.blurple) async def survey(self, interaction: discord.Interaction, button: discord.ui.Button): user_id = interaction.user.id # 检查用户是否已发起过问卷 if user_id in self.clicked_users: await interaction.response.send_message("你已经发起过问卷了,无法重复操作哦", ephemeral=True) return # 记录该用户已点击 self.clicked_users.add(user_id) # 发送问卷 view = questions() await interaction.response.send_message(content="", embed=surveyEmbed, view=view, ephemeral=True)
注意
- 若bot重启,
clicked_users集合会被清空,用户可重新点击。如果需要永久限制用户提交,需将用户ID存入数据库(如SQLite、MongoDB),每次检查时从数据库读取记录。
二、设置用户点击冷却时间
通过记录用户上次点击的时间戳,实现指定时间内用户无法重复点击。
修改后的代码如下:
import discord import time class surveyView(discord.ui.View): def __init__(self): super().__init__(timeout=None) self.value = None # 存储用户上次点击的时间戳,键为用户ID self.cooldowns = {} # 自定义冷却时间(单位:秒) self.COOLDOWN_DURATION = 60 @discord.ui.button(label="Let's get started!", style=discord.ButtonStyle.blurple) async def survey(self, interaction: discord.Interaction, button: discord.ui.Button): user_id = interaction.user.id current_time = time.time() # 检查是否在冷却期内 if user_id in self.cooldowns: elapsed_time = current_time - self.cooldowns[user_id] if elapsed_time < self.COOLDOWN_DURATION: remaining_time = int(self.COOLDOWN_DURATION - elapsed_time) await interaction.response.send_message(f"请再等待{remaining_time}秒后重新发起问卷", ephemeral=True) return # 更新用户的点击时间 self.cooldowns[user_id] = current_time # 发送问卷 view = questions() await interaction.response.send_message(content="", embed=surveyEmbed, view=view, ephemeral=True)
注意
- 同样,bot重启后
cooldowns字典会重置,若需要持久化冷却记录,需将用户ID和点击时间存入数据库。
内容的提问来源于stack exchange,提问作者Ryan Thomas
相关产品推荐
相关产品推荐

