Py-Cord中如何动态修改Slash Command的选项列表?
问题分析
你遇到的核心问题是:Py-Cord的斜杠命令选项choices是在机器人启动时同步到Discord API的,之后修改本地变量air不会自动更新Discord端的命令选项缓存。所以哪怕你修改了全局变量air,Discord那边的select_role命令选项还是初始的空列表。
解决方案
使用Py-Cord的**自动补全(Autocomplete)**功能,它会在用户触发命令时实时获取最新的选项列表,完美适配动态更新的需求。
修改后的完整代码
import shutil import discord from discord import Option, AutocompleteContext from discord.ext import commands bot = commands.Bot(intents=discord.Intents.all()) # 全局存储飞机选项 air = [] # 自动补全函数:实时返回当前的air列表 async def aircraft_autocomplete(ctx: AutocompleteContext): return air @bot.slash_command(name="operation_select") async def operation_select(ctx, mission: Option(str, "Select A Mission", choices=["Night Terror", "Other"]), ): global air if mission == "Night Terror": air = ["AH64D", "MI24", "KA50"] elif mission == "Other": air = ["1", "2"] # 修正文件复制路径(原代码里的"EENight Terror.txt"若为笔误可自行调整) shutil.copyfile("EENight Terror.txt", "Night Terror.txt") with open(f"{mission}.txt", "r") as file: await ctx.respond(file.read()) @bot.slash_command(name="select_role", description="Select your role") async def role_select(ctx, # 使用autocomplete绑定动态选项 aircraft: Option(str, "Select your aircraft", autocomplete=aircraft_autocomplete) ): await ctx.send(f"你选择了:{aircraft}") bot.run("你的TOKEN")
关键修改点
- 添加自动补全函数:
aircraft_autocomplete会在用户调用select_role时实时返回当前的air列表,替代了固定的choices参数。 - 修正全局变量声明:在
operation_select内正确使用global air来修改全局变量(原代码中global位置错误,需放在赋值操作前)。 - 修复语法错误:补全了原代码中
Night Terror分支未闭合的air = [语句。
为什么原来的方法无效?
Discord的斜杠命令需要提前注册,机器人启动时会把所有命令的结构(包括选项的choices)发送给Discord API,之后这些信息会被Discord缓存。单纯修改本地变量不会触发重新同步,所以Discord端的选项不会更新。而自动补全是每次用户输入时动态请求最新选项,避开了缓存问题。
内容的提问来源于stack exchange,提问作者Stevon
相关产品推荐
相关产品推荐

