简体   繁体   中英

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

Try that:

async def list_search(ctx: discord.AutocompleteContext):
"""Return's A List Of Autocomplete Results"""
return your_list # from your database


@bot.slash_command(name="ac_example")
    async def autocomplete_example(
        ctx: discord.ApplicationContext,
        choice: Option(str, "what will be your choice!", autocomplete=list_search),
    ):
        await ctx.respond(f"You picked {choice}!")
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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM