如何在Discord.py中实现每次调用命令时随机打乱按钮位置?
解决Discord按钮随机排序问题
你当前的按钮位置固定,是因为用@discord.ui.button装饰器定义的按钮会按定义顺序自动加入View,所以b1永远在左、b2在中、b3在右。要实现随机打乱,得改成动态创建按钮实例,打乱后再添加到View,具体修改如下:
修改后的完整代码
import random import string import discord class ButtonView(discord.ui.View): def __init__(self, code, *, timeout=20): super().__init__(timeout=timeout) self.code = code self.solved = None self.failed = 0 # 正确按钮的回调逻辑 async def correct_callback(interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message("Good!!") self.solved = True self.stop() # 错误按钮的通用回调逻辑 async def wrong_callback(interaction: discord.Interaction, button: discord.ui.Button): self.failed += 1 if self.failed >= 2: await interaction.response.send_message(f"Too many incorrect attempts. Kicking {interaction.user.mention}") await interaction.user.kick(reason="Too many incorrect captcha attempts.") await log_attempt(interaction.user, success=False) self.stop() else: await interaction.response.send_message("Wrong!!") self.solved = False # 创建三个按钮实例:1个正确,2个错误 buttons = [ discord.ui.Button(label=code, style=discord.ButtonStyle.gray, callback=correct_callback), discord.ui.Button(label=''.join(random.sample(string.digits, 4)), style=discord.ButtonStyle.gray, callback=wrong_callback), discord.ui.Button(label=''.join(random.sample(string.digits, 4)), style=discord.ButtonStyle.gray, callback=wrong_callback) ] # 打乱按钮顺序 random.shuffle(buttons) # 将打乱后的按钮添加到View中 for btn in buttons: self.add_item(btn)
关键改动说明
- 移除了原有用装饰器固定顺序的
b1/b2/b3方法,改用通用回调函数,避免按钮顺序被硬编码固定 - 手动创建按钮实例后,用
random.shuffle()打乱列表顺序,再通过add_item()添加到View,实现每次调用时位置随机 - 合并了原b2和b3的重复错误逻辑,减少冗余代码,同时保留原有验证规则
这样每次用户触发命令生成View时,三个按钮的位置都会随机打乱,同时完全保留你原来的验证功能。
内容的提问来源于stack exchange,提问作者luffy
相关产品推荐
相关产品推荐

