zaber8787利巴
zaber8787利巴

Reputation: 1

Make discord generate search result

I want to create a music bot where users can search for keywords to get search results and then choose the song they want to listen to through a Select menu. However, I don't know how to add the search results to select options.

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]}")

Upvotes: 0

Views: 44

Answers (1)

Raymus
Raymus

Reputation: 1305

Select menus use the options attribute to determine what options the select menu will have.

Since the search results will change every time it is called, a static select menu with fixed options won't do. For this, we can dynamically add the select menu.

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)

This code creates a new method add_select to dynamically add the select menu. The list options is a list of SelectOptions which are added to the select menu. Then we assign the select menu the callback. Finally, using the add_item method, we add the select menu to the view class.

For more information: discord.ui.Select, Select.options, discord.SelectOption, discord.ui.View, View.add_item

Upvotes: 0

Related Questions