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

使用disnake如何通过斜杠命令的按钮获取选中选项?

解决disnake中按钮回调获取斜杠命令选项的问题

要在按钮的回调函数中获取对应斜杠命令的选中选项,核心思路是把斜杠命令的选项传递给View实例——每个View实例和当前命令的消息绑定,回调时直接从View中读取存储的选项数据即可。

方法一:传递单个指定选项

修改ButtonView类的初始化方法,接收需要的选项并保存,之后在按钮回调中直接访问:

class ButtonView(disnake.ui.View):
    def __init__(self, command_id: str):
        super().__init__(timeout=None)
        # 存储斜杠命令的id选项
        self.command_id = command_id

    @disnake.ui.button(label="button", style=disnake.ButtonStyle.red)
    async def first_button(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
        # 在回调中使用存储的id参数
        await inter.response.send_message(f"你输入的ID是:{self.command_id}", ephemeral=True)

@bot.slash_command() 
async def test(inter: disnake.ApplicationCommandInteraction, id: str):
    # 创建View时传入当前命令的id参数
    await inter.send("slash command", view=ButtonView(command_id=id))

方法二:传递完整选项对象

如果需要获取多个选项,可以直接传递inter.options对象,后续在回调中按需提取:

class ButtonView(disnake.ui.View):
    def __init__(self, options):
        super().__init__(timeout=None)
        self.options = options

    @disnake.ui.button(label="button", style=disnake.ButtonStyle.red)
    async def first_button(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
        # 从options中提取需要的参数
        input_id = self.options.get("id")
        await inter.response.send_message(f"你输入的ID是:{input_id}", ephemeral=True)

@bot.slash_command() 
async def test(inter: disnake.ApplicationCommandInteraction, id: str):
    await inter.send("slash command", view=ButtonView(options=inter.options))

注意事项

  • 每次调用斜杠命令都会生成新的ButtonView实例,因此每个按钮对应的View只会持有该次命令的专属选项数据,不会出现数据混淆。
  • 如果你的View设置了timeout=None(持久化视图),上述传参方式依然适用,只需确保持久化视图的注册逻辑正确即可。

内容的提问来源于stack exchange,提问作者I am pk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:38