我想创建一个音乐机器人,用户可以搜索关键字来获取搜索结果,然后通过选择菜单选择他们想听的歌曲。但是,我不知道如何将搜索结果添加到选择选项中。
class MyView(discord.ui.View):
def __init__(self, url, update):
super().__init__()
self.update = update #To update the url in the queue
self.url = url
options = []
for i in url:
title = i['title'][:20]
options.append(discord.ui.select(
discord.SelectOption(label=title)))
@discord.ui.select(
placeholder="song",
min_values=1,
max_values=1
)
async def select_callback(self, select, interaction):
self.update(select.values[0]) #To update the url in the queue
await interaction.response.send_message(f"You choose {select. Values[0]}")
Select 菜单使用 options 属性来确定选择菜单将具有哪些选项。
由于每次调用时搜索结果都会改变,因此具有固定选项的静态选择菜单是行不通的。为此,我们可以动态添加选择菜单。
class MyView(discord.ui.View):
def __init__(self, url, update):
super().__init__()
self.url = url
...
self.add_select()
def add_select(self):
options = []
# Append search results to options
select = discord.ui.Select(placeholder="song",
options=options)
async def select_callback(interaction: discord.Interaction):
# Callback function
select.callback = select_callback
self.add_item(select)
此代码创建了一个新方法
add_select
来动态添加选择菜单。列表 options
是添加到选择菜单的 SelectOption 列表。然后我们为选择菜单分配回调。最后,使用 add_item 方法,我们将选择菜单添加到视图类中。
了解更多信息:discord.ui.Select、Select.options、discord.SelectOption、discord.ui.View、View.add_item