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

discord.py如何为斜杠命令响应添加按钮?遇参数缺失报错求助

解决discord.py斜杠命令添加按钮时的TypeError问题

你的错误根源是把按钮回调函数直接当作View使用了。discord.py要求按钮必须放在继承自discord.ui.View的类中,不能单独用装饰器定义回调函数后直接实例化当View传参。

下面是修正后的代码:

# 定义继承自View的类,所有按钮逻辑都要封装在这里
class TestView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)  # timeout=None可让按钮永久有效,按需调整时长

    @discord.ui.button(label='test', style=discord.ButtonStyle.grey)
    async def asdf(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message('workie', ephemeral=True)
        print("yes")

@bot.tree.command(name="tester", description="tester")
async def hello(interaction: discord.Interaction):
    # 实例化自定义View类,作为view参数传入
    await interaction.response.send_message("tester", view=TestView())

关键修正点:

  • 新增TestView类继承discord.ui.View,按钮回调函数asdf作为类的方法存在
  • 斜杠命令里传入的view是TestView()的实例,而非原代码里的asdf()
  • 斜杠命令参数命名为interaction更符合discord.py规范(和参数类型discord.Interaction统一,避免混淆)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 06:34:58