pythondiscord.py

Dynamic select from list for discord bot


I send a modal to the user and expect a response from the user, after receiving it, it is processed and receives a list (there are no more than 20 elements in the list), and also sends a select to the user with a choice from this list. I got this error:

for character in character_in_raid ['name']]
                     ^^^^^^^^^^^^^^^^^
NameError: name 'character_in_raid' is not defined

This is my current code:

class logs_input(discord.ui.Modal, title="Test"):
    tst = discord.ui.TextInput(label="1")    
    async def on_submit(self, interaction: discord.Interaction):
        log_code = self.tst.value
        response = get_token()
        store_token(response)
        log_parse = get_logs.log_character(log_code)
        global character_in_raid
        character_in_raid = log_parse['rankedCharacters']
        for character in character_in_raid:
            print(character)
        await interaction.response.send_message(view=Select_buyer())


class Select_buyer(discord.ui.View):
        
    @discord.ui.select(
        placeholder = "Choose buyer",
        min_values=0, max_values=20, 
        options= [discord.SelectOption
            (label=character['name'], value=character['name'])
                 for character in character_in_raid ['name']]
    )

    async def buyer_select(self, interaction: discord.Interaction, select: discord.ui.Select):
        selected_values = select.values
        print(selected_values)
        await interaction.response.send_message(selected_values)

I tried making the variable global, but it didn't help. Can anyone help me with this? I'll appreciate any guidance. Thanks in advance!


Solution

  • Try this:

    class _Select(discord.ui.Select):
            def __init__(self, list_options:List[discord.SelectOption]):
                super().__init__(options=list_options)
    
            async def callback(self, interaction: discord.Interaction):
                  selected_values = self.values
                  await interaction.response.send_message(selected_values)
    
    class Select_buyer(discord.ui.View):
        def __init__(self, list_options:List[discord.SelectOption]):
            super().__init__()
            self.component=_Select(list_options)
            self.add_item(self.component)
    

    And then, at the end of your logs_input class

    options = [discord.SelectOption(label=character['name'], value=character['name']) for character in character_in_raid]
    await interaction.response.send_message(view=Select_buyer(list_options=options))