pythondiscorddiscord.pyslashpycord

Pycord dynamically slash-command option choices from DB


I try use dynamically slash command from database value i'm using sqlite3 and my database name is server id so for connection to database i have to use ctx.guild.id and now i can't use this command outside method in Cogs but i have to use that command to get value from my query:

    @commands.guild_only()
    @commands.slash_command(name = 'add',description = "Add member to group.")
    async def add_user(self,ctx,
                       name:Option(str,"User name",required=True),
                       role:Option(str,"User role",required=False,),
                       _class:Option(str,"User class",required=False,choices = [])):

Here is my database handle

@commands.command()     
    async def check_classes(self,ctx):
        conn = sqlite3.connect(f"databases//{ctx.guild.name} - {str(ctx.guild.id)}.db")
        cursor = conn.cursor()
        cursor.execute(f"SELECT class,Iconclass FROM Classes")
        rows = cursor.fetchall()
        conn.commit()
        conn.close()
        return rows

I don't have idea how to get this value from database and put it choices option


Solution

  • async def get_list_from_db(ctx: discord.AutocompleteContext):
    """Returns list of items from db, sorted in such a way that Pycord can autocomplete"""
        ... # Code where you fetch data from db
        return sorted([i for i in db_list if i.startswith(ctx.value.lower())])
    
    @slash_command()
    async def autocomplete_example(
        self,
        ctx: discord.ApplicationContext,
        db_item: discord.Option(str, "Select an item", autocomplete=get_list_from_db),
    ):
        await ctx.respond(f"You picked {db_item}")