我的代码需要帮助。我正在尝试为我的不和谐机器人制作按钮。我设法做到了,但我想添加一些新的东西。如您所见,b1 始终位于左侧,b2 位于中间,b3 位于右侧。每次用户输入命令时是否可以改变按钮位置。任何帮助,将不胜感激。下面我附上了我的代码。谢谢!
class ButtonView(discord.ui.View):
def __init__(self, code, *, timeout=20):
super().__init__(timeout=timeout)
self.code = code
self.solved = None
self.failed = 0
self.b1.label = code
self.b2.label = ''.join(random.sample(string.digits, 4))
self.b3.label = ''.join(random.sample(string.digits, 4))
@discord.ui.button(style=discord.ButtonStyle.gray)
async def b1(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message("Good!!")
self.solved = True
self.stop()
@discord.ui.button(style=discord.ButtonStyle.gray)
async def b2(self, 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)
else:
await interaction.response.send_message("Wrong!!")
self.solved = False
if self.failed >= 2:
self.stop()
@discord.ui.button(style=discord.ButtonStyle.gray)
async def b3(self, 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)
else:
await interaction.response.send_message("Also wrong!!")
self.solved = False
if self.failed >= 2:
self.stop()
通过动态添加按钮,您可以更改它们添加到视图中的顺序。
import random
class ButtonView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_buttons()
def add_buttons(self):
buttons = [
discord.ui.Button(label="Button 1"),
discord.ui.Button(label="Button 2"),
discord.ui.Button(label="Button 3")
]
buttons[0].callback = ... # Or set them as variables first
buttons[1].callback = ... # then put them into a list
buttons[2].callback = ...
random.shuffle(buttons) # Randomises the order
for button in buttons:
self.add_item(button)
此示例使用函数
add_buttons
在初始化视图时将按钮动态添加到视图中。
视图将按照添加的顺序显示按钮;就像您对按钮装饰器所做的那样,这里的按钮位于列表中,然后按随机顺序进行添加。
如果随机化不是您想要的,您也可以使用相同的方法来更改按钮。
def add_buttons(self):
if ...: # Some condition
button = ... # Button object
button.callback = ... # Callback function
self.add_item(button)
也不需要
for
循环,只要将按钮按特定顺序添加到视图类中,它们就会按该顺序出现。