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
相关产品推荐
相关产品推荐

