You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py中实现斜杠命令的动态参数切换?

在discord.py中实现动态斜杠命令参数

要实现你需要的动态参数效果,核心是利用discord.py的**自动完成(Autocomplete)**功能,根据第一个参数的选择动态生成第二个参数的可选值。以下是具体实现步骤和代码示例:

1. 基础准备

确保你的discord.py版本≥2.0,斜杠命令和自动完成功能是v2版本引入的核心特性。

2. 实现自动完成函数

编写一个自动完成函数,根据用户选择的region参数,返回对应的菜系选项:

from discord import app_commands
from discord.ext import commands
import discord

async def cuisine_autocomplete(interaction: discord.Interaction, current: str):
    # 获取用户已选择的region参数值
    region = interaction.data.get('options', [{}])[0].get('value')
    
    # 根据region返回对应菜系选项
    if region == 'asian':
        choices = [
            app_commands.Choice(name='korean', value='korean'),
            app_commands.Choice(name='japanese', value='japanese'),
            app_commands.Choice(name='chinese', value='chinese')
        ]
    elif region == 'european':
        choices = [
            app_commands.Choice(name='german', value='german'),
            app_commands.Choice(name='french', value='french'),
            app_commands.Choice(name='english', value='english')
        ]
    else:
        choices = []
    
    # 过滤匹配用户当前输入的选项(可选,提升体验)
    return [choice for choice in choices if current.lower() in choice.name.lower()]

3. 定义斜杠命令

将自动完成函数绑定到cuisine参数上,同时给region参数设置固定可选值:

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix='!', intents=discord.Intents.default())

    async def setup_hook(self):
        await self.tree.sync()

bot = MyBot()

@bot.tree.command(name='food', description='选择地区对应的菜系')
@app_commands.describe(region='选择地区', cuisine='选择菜系')
@app_commands.autocomplete(cuisine=cuisine_autocomplete)
@app_commands.choices(region=[
    app_commands.Choice(name='asian', value='asian'),
    app_commands.Choice(name='european', value='european')
])
async def food(interaction: discord.Interaction, region: str, cuisine: str):
    await interaction.response.send_message(f'你选择了{region}地区的{cuisine}菜系!')

# 运行机器人
bot.run('你的Bot令牌')

关键说明

  • interaction.data:通过这个属性可以获取用户当前已经输入的命令参数,从而判断第一个参数region的选择值。
  • 自动完成函数返回的app_commands.Choice列表,会实时显示在Discord的命令输入框中,用户只能选择列表内的选项。
  • 过滤逻辑current.lower() in choice.name.lower()是为了让用户输入部分字符时,能匹配到对应的选项,提升交互体验。

内容的提问来源于stack exchange,提问作者Snap_Lan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:02:34