如何修复Discord.py中‘TypeError: Menu2.button_callback()缺少必填参数button’错误?
解决Discord.py中按钮回调的TypeError问题
错误出在Menu2类手动绑定按钮回调的方式上:当使用@discord.ui.button装饰器时,discord.py会自动将按钮实例作为第二个参数传入回调函数,但手动给button.callback赋值时,回调函数只会收到interaction这一个参数,导致你定义的button_callback要求的第二个button参数缺失,触发TypeError。
以下是两种可行的解决方法:
方案一:修改回调函数参数,移除button参数
如果不需要在回调里直接调用按钮实例,可直接删除button参数;若需要按钮相关信息,也可通过interaction.component获取:
class Menu2(View): def __init__(self, ctx): super().__init__() self.ctx = ctx options = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] for option in options: button = discord.ui.Button(label=option, style=discord.ButtonStyle.green, emoji="📜") button.callback = self.button_callback self.add_item(button) async def interaction_check(self, interaction: discord.Interaction): if interaction.user == self.ctx.author: return True await interaction.response.send_message("You can't interact with this menu.", ephemeral=True) return False # 移除button参数,或通过interaction.component获取按钮信息 async def button_callback(self, interaction: discord.Interaction): # 如需按钮信息,可取消注释下面这行 # button = interaction.component await interaction.response.send_message('You Clicked it')
方案二:用functools.partial绑定button参数
如果必须在回调中直接使用按钮实例,可借助functools.partial将按钮对象绑定到回调函数中:
首先导入functools模块:
import functools
然后修改Menu2类的初始化逻辑:
class Menu2(View): def __init__(self, ctx): super().__init__() self.ctx = ctx options = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"] for option in options: button = discord.ui.Button(label=option, style=discord.ButtonStyle.green, emoji="📜") # 用partial将button参数绑定到回调函数 button.callback = functools.partial(self.button_callback, button=button) self.add_item(button) async def interaction_check(self, interaction: discord.Interaction): if interaction.user == self.ctx.author: return True await interaction.response.send_message("You can't interact with this menu.", ephemeral=True) return False # 保留原参数签名 async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button): await interaction.response.send_message(f'You Clicked {button.label}!')
内容的提问来源于stack exchange,提问作者Jake Noguera
相关产品推荐
相关产品推荐

