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

Discord按钮交互失败:TypeError参数缺失问题求助

修复Discord按钮回调"interaction failed"错误

问题根源

你的代码报错是因为按钮回调函数的参数签名不符合discord.py的要求:discord.py中UI组件的回调函数仅需接收一个必选参数interaction(交互对象),你额外添加的button参数会导致调用时参数不匹配,从而触发"missing required positional argument"错误。

修复方案

方案1:通过Interaction对象获取按钮信息(推荐)

利用你已经设置的custom_id=option,直接从交互数据中提取点击的按钮标签,或从View的子组件中匹配对应按钮:

from discord.ui import View, Button
import discord

class MyView(View):
    def __init__(self, options):
        super().__init__()
        self.options = options
        
        for option in options:
            button = Button(label=option, custom_id=option)
            button.callback = self.on_button_click  
            self.add_item(button) 

    async def on_button_click(self, interaction: discord.Interaction):
        # 直接从交互数据中获取custom_id(即按钮标签)
        clicked_label = interaction.data['custom_id']
        await interaction.response.send_message(f"You clicked: {clicked_label}")

        # 若需获取按钮实例,可使用以下代码:
        # clicked_button = next(item for item in self.children if isinstance(item, Button) and item.custom_id == interaction.data['custom_id'])
        # await interaction.response.send_message(f"You clicked: {clicked_button.label}")

方案2:用functools.partial绑定按钮实例

如果需要在回调中直接操作按钮对象(比如修改按钮状态),可以用functools.partial将按钮实例绑定到回调参数:

from discord.ui import View, Button
import discord
from functools import partial

class MyView(View):
    def __init__(self, options):
        super().__init__()
        self.options = options
        
        for option in options:
            button = Button(label=option, custom_id=option)
            # 绑定button到回调的第一个参数,留interaction作为第二个参数
            button.callback = partial(self.on_button_click, button)
            self.add_item(button) 

    async def on_button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.send_message(f"You clicked: {button.label}")

注意事项

  • 方案1更贴合discord.py原生设计,无需额外依赖,优先推荐。
  • 方案2使用时需注意partial的参数顺序:提前绑定的参数放在前面,最后保留interaction参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:13:12