简体   繁体   English

来自 DB 的 Pycord 动态斜杠命令选项选择

[英]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:我尝试从数据库值中使用动态斜杠命令我正在使用 sqlite3 并且我的数据库名称是服务器 id 所以为了连接到数据库我必须使用 ctx.guild.id 现在我不能在 Cogs 中使用这个命令之外的方法但是我必须使用该命令从我的查询中获取值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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