
本文旨在解决 discord.py 中交互按钮常见的“interaction error”问题。核心在于理解按钮回调函数(如 `agree_btn`)的正确参数签名,即只应包含 `self`、`interaction` 和 `button`。文章将详细解释错误原因,并提供两种安全有效的数据传递方法:通过 `view` 类的 `__init__` 方法传递数据,以及更高级的持久化存储方案,确保按钮功能正常且数据可访问。
在使用 Discord.py 2.0+ 版本开发机器人时,交互按钮(discord.ui.Button)是实现丰富用户体验的重要组件。然而,开发者常会遇到一个“interaction error”,尤其是在尝试向按钮的回调函数中传递额外参数时。
按钮回调函数的标准签名
discord.ui.button 装饰器修饰的方法,其回调函数签名是严格规定的。它通常期望接收三个参数:
任何额外的参数,如 user: discord.Member,都会导致 Discord 无法正确解析回调,从而引发“interaction error”。
考虑以下一个模拟求婚系统的代码片段,它试图在按钮回调中直接使用 user 参数:
import discord
# 假设 client 已初始化并与 Discord 连接
# client = discord.Client(intents=discord.Intents.default())
# tree = discord.app_commands.CommandTree(client)
class MarryButtons(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Yes", style=discord.ButtonStyle.success)
async def agree_btn(self, interaction: discord.Interaction, button: discord.ui.Button, user: discord.Member):
# 错误:这里多了一个 user 参数
embed_agree = discord.Embed(title=f'{user.mention} answered YES', description=f'{user.mention} now married to {interaction.user.mention}')
await interaction.response.send_message(embed=embed_agree)
@discord.ui.button(label="No", style=discord.ButtonStyle.danger)
async def disagree_btn(self, interaction: discord.Interaction, button: discord.ui.Button, user: discord.Member):
# 错误:这里多了一个 user 参数
embed_disagree = discord.Embed(title=f'{user.mention} answered NO', description=f'{user.mention} declined propose from {interaction.user.mention}')
await interaction.response.send_message(embed=embed_disagree)
@discord.ui.button(label="?", style=discord.ButtonStyle.gray)
async def emoji_btn(self, interaction: discord.Interaction, button: discord.ui.Button, user: discord.Member):
# 错误:这里多了一个 user 参数
embed_emoji = discord.Embed(title=f'{user.mention} canceled propose', description=f'Nothing changed')
await interaction.response.send_message(embed=embed_emoji)
# 假设这是一个 slash command
# @tree.command(name='marry', description="Suggest to marry")
# async def marry(interaction: discord.Interaction, user: discord.Member):
# if interaction.user == user:
# await interaction.response.send_message(content=f"{interaction.user.mention} you can't marry yourself :(")
# return
# else:
# embed_marry = discord.Embed(title='WOW.....', description=f'{interaction.user.mention} suggest a marry to {user.mention}', color=0x774dea)
# await interaction.response.send_message(embed=embed_marry, view=MarryButtons())当用户点击上述代码中的按钮时,Discord 会尝试调用 agree_btn 等方法,但由于其签名与预期不符(多了一个 user 参数),就会导致“interaction error”。
要解决这个问题,我们需要移除回调函数中多余的参数,并采用其他机制来传递数据。
最常见且推荐的做法是将需要在按钮回调中访问的数据,在 View 类实例化时通过其 __init__ 方法传递进去,并作为实例属性存储。这样,按钮回调函数就可以通过 self.<attribute_name> 来访问这些数据。
以下是修正后的求婚系统代码示例:
import discord
# 假设 client 已初始化并与 Discord 连接
# client = discord.Client(intents=discord.Intents.default())
# tree = discord.app_commands.CommandTree(client)
class MarryButtons(discord.ui.View):
def __init__(self, proposer: discord.Member, target: discord.Member):
super().__init__(timeout=180) # 设置一个超时时间,防止视图永久存在
self.proposer = proposer
self.target = target
@discord.ui.button(label="Yes", style=discord.ButtonStyle.success)
async def agree_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 确保只有被求婚者才能点击“Yes”或“No”
if interaction.user != self.target:
await interaction.response.send_message("你不是被求婚者,无法操作。", ephemeral=True)
return
embed_agree = discord.Embed(
title=f'{self.target.display_name} 接受了求婚!',
description=f'{self.target.mention} 现在与 {self.proposer.mention} 喜结连理。',
color=discord.Color.green()
)
# 禁用所有按钮,防止重复点击
self.stop() # 停止视图,防止进一步交互
await interaction.response.edit_message(embed=embed_agree, view=None) # 移除按钮
# 也可以发送新的消息
# await interaction.response.send_message(embed=embed_agree)
@discord.ui.button(label="No", style=discord.ButtonStyle.danger)
async def disagree_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user != self.target:
await interaction.response.send_message("你不是被求婚者,无法操作。", ephemeral=True)
return
embed_disagree = discord.Embed(
title=f'{self.target.display_name} 拒绝了求婚。',
description=f'{self.target.mention} 拒绝了 {self.proposer.mention} 的求婚。',
color=discord.Color.red()
)
self.stop() # 停止视图
await interaction.response.edit_message(embed=embed_disagree, view=None) # 移除按钮
@discord.ui.button(label="?", style=discord.ButtonStyle.gray)
async def emoji_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 允许求婚者或被求婚者取消
if interaction.user not in [self.proposer, self.target]:
await interaction.response.send_message("你无权取消此求婚。", ephemeral=True)
return
embed_emoji = discord.Embed(
title='求婚已取消',
description='求婚被发起人或被求婚者取消,状态未改变。',
color=discord.Color.light_gray()
)
self.stop() # 停止视图
await interaction.response.edit_message(embed=embed_emoji, view=None) # 移除按钮
# 假设 client 和 tree 已初始化
# client = discord.Client(intents=discord.Intents.default())
# tree = discord.app_commands.CommandTree(client)
@tree.command(name='marry', description="向某人求婚")
async def marry(interaction: discord.Interaction, user: discord.Member):
if interaction.user == user:
await interaction.response.send_message(content=f"{interaction.user.mention} 你不能向自己求婚 :(", ephemeral=True)
return
# 实例化 MarryButtons 时传入求婚者和被求婚者
view = MarryButtons(proposer=interaction.user, target=user)
embed_marry = discord.Embed(
title='? 惊喜求婚!',
description=f'{interaction.user.mention} 向 {user.mention} 发起了求婚!',
color=0x774dea
)
await interaction.response.send_message(embed=embed_marry, view=view)
# 在机器人启动时同步命令
# @client.event
# async def on_ready():
# print(f'Logged in as {client.user}')
# await tree.sync()
# print('Commands synced')
# client.run('YOUR_BOT_TOKEN')代码改进点说明:
对于需要管理多个并发请求或更复杂状态的系统,仅仅通过 View 实例传递数据可能不够。在这种情况下,可以考虑使用:
这种方法更健壮,但实现起来也更复杂,需要额外的逻辑来管理数据的存储、检索和清理。
通过遵循这些原则,开发者可以有效地利用 Discord.py 的交互按钮功能,构建稳定且用户友好的机器人应用。
以上就是Discord.py 交互按钮回调参数错误及数据传递指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号