
本文旨在解决discord.py中`discord.ui.button`回调函数常见的“interaction error”,该错误通常由不正确的参数签名引起。我们将详细解释回调函数应有的参数结构,并提供两种有效方法来向按钮回调函数传递必要的上下文数据(如原始命令中的用户对象),从而确保交互的正确性和功能的完整性。
在使用 Discord.py 构建交互式机器人时,按钮(Buttons)是实现丰富用户体验的重要组件。然而,开发者在使用 discord.ui.Button 时常会遇到“interaction error”,这通常是由于对按钮回调函数参数的误解造成的。本教程将深入探讨这一问题,并提供一套完整的解决方案,包括参数修正和上下文数据传递策略。
discord.ui.Button 的回调函数(即装饰器 @discord.ui.button 所修饰的方法)有一个固定的参数签名。当用户点击按钮时,Discord API 会向机器人发送一个交互事件,Discord.py 库会将这个事件解析并作为特定参数传递给回调函数。
标准的按钮回调函数签名如下:
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
# ... 处理交互逻辑 ...任何额外的、非预期的参数都会导致 Discord 报告“interaction error”,因为库无法正确地将事件数据映射到这些额外的参数上。
根据提供的代码片段,错误发生的原因在于按钮回调函数中额外添加了 user: discord.Member 参数:
# 原始错误代码示例
class MarryButtons(discord.ui.View):
# ...
@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: discord.Member 参数是 Discord.py 库在处理按钮点击事件时不会自动提供的。当用户点击按钮时,库只会提供 self、interaction 和 button。因此,当回调函数被调用时,Python 解释器无法为 user 参数找到对应的值,从而导致内部错误,并最终表现为 Discord 客户端的“interaction error”。
解决这个问题的直接方法是移除按钮回调函数中所有非标准参数。将所有按钮回调函数(agree_btn、disagree_btn、emoji_btn)的签名修正为标准形式:
import discord
# 修正后的 MarryButtons 类(暂时不考虑 user 参数的获取)
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):
# 修正后的逻辑,暂时无法直接获取被求婚者
proposer = interaction.message.embeds[0].description.split(' ')[0] # 示例:从嵌入消息中解析
await interaction.response.send_message(content=f"{interaction.user.mention} 同意了 {proposer} 的求婚!")
self.stop() # 停止 View 监听
@discord.ui.button(label="No", style=discord.ButtonStyle.danger)
async def disagree_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
proposer = interaction.message.embeds[0].description.split(' ')[0]
await interaction.response.send_message(content=f"{interaction.user.mention} 拒绝了 {proposer} 的求婚。")
self.stop()
@discord.ui.button(label="?", style=discord.ButtonStyle.gray)
async def emoji_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
proposer = interaction.message.embeds[0].description.split(' ')[0]
await interaction.response.send_message(content=f"{interaction.user.mention} 取消了 {proposer} 的求婚提议。")
self.stop()
# 命令示例
# @client.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} 你不能和自己结婚 :(")
# return
# else:
# embed_marry = discord.Embed(title='WOW.....', description=f'{interaction.user.mention} 提议向 {user.mention} 求婚', color=0x774dea)
# await interaction.response.send_message(embed=embed_marry, view=MarryButtons())通过上述修正,按钮点击时将不再出现“interaction error”。然而,新的问题是,如何在按钮回调函数中获取到 marry 命令中传递的 user (被求婚者) 对象呢?这需要我们将上下文数据从命令传递到 View 实例。
有两种主要方法可以将命令中的上下文数据传递给按钮回调函数:
这是最直接且常用的方法。在创建 discord.ui.View 实例时,将所需的上下文数据作为参数传递给其 __init__ 方法,并将其存储为 View 实例的属性。这样,按钮回调函数就可以通过 self 访问这些属性。
1. 修改 MarryButtons 类的 __init__ 方法:
import discord
class MarryButtons(discord.ui.View):
def __init__(self, proposer: discord.Member, target_user: discord.Member):
super().__init__(timeout=180) # 设置超时时间,例如3分钟
self.proposer = proposer
self.target_user = target_user
@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_user:
await interaction.response.send_message("你不是被求婚者,无法操作此按钮!", ephemeral=True)
return
embed_agree = discord.Embed(
title='恭喜!',
description=f'{self.target_user.mention} 同意了 {self.proposer.mention} 的求婚!他们现在结婚了!',
color=discord.Color.green()
)
await interaction.response.edit_message(embed=embed_agree, view=None) # 移除按钮
self.stop() # 停止 View 监听
@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_user:
await interaction.response.send_message("你不是被求婚者,无法操作此按钮!", ephemeral=True)
return
embed_disagree = discord.Embed(
title='很遗憾',
description=f'{self.target_user.mention} 拒绝了 {self.proposer.mention} 的求婚。',
color=discord.Color.red()
)
await interaction.response.edit_message(embed=embed_disagree, view=None) # 移除按钮
self.stop()
@discord.ui.button(label="?", style=discord.ButtonStyle.gray)
async def emoji_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 任何人都可以取消,但通常只有发起者或被求婚者才有意义
if interaction.user != self.proposer and interaction.user != self.target_user:
await interaction.response.send_message("你无法取消此求婚。", ephemeral=True)
return
embed_emoji = discord.Embed(
title='求婚取消',
description=f'{interaction.user.mention} 取消了 {self.proposer.mention} 向 {self.target_user.mention} 的求婚提议。',
color=discord.Color.light_gray()
)
await interaction.response.edit_message(embed=embed_emoji, view=None) # 移除按钮
self.stop()
async def on_timeout(self):
# 当 View 超时时执行
message = self.message # 获取 View 关联的消息
if message:
embed = message.embeds[0]
embed.title = '求婚超时'
embed.description = f'{self.proposer.mention} 向 {self.target_user.mention} 的求婚请求已超时,未得到回应。'
embed.color = discord.Color.orange()
await message.edit(embed=embed, view=None) # 移除按钮2. 在命令中实例化 MarryButtons 时传递参数:
import discord
from discord.ext import commands
# 假设 client 已经初始化
# client = commands.Bot(command_prefix='!', intents=discord.Intents.all())
# @client.event
# async def on_ready():
# print(f'Logged in as {client.user}')
# await client.tree.sync() # 同步命令
@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 实例时传递 proposer 和 target_user
view = MarryButtons(proposer=interaction.user, target_user=user)
embed_marry = discord.Embed(
title='求婚进行中...',
description=f'{interaction.user.mention} 向 {user.mention} 提议求婚!请 {user.mention} 点击按钮回应。',
color=0x774dea
)
# 发送消息并关联 View
await interaction.response.send_message(embed=embed_marry, view=view)
# 存储消息对象到 View 实例,以便在 on_timeout 中访问
view.message = await interaction.original_response() 对于更复杂的场景,例如需要处理多个并发的求婚请求,或者需要在机器人重启后仍然保留状态,将上下文数据存储在数据库(如 SQLite, PostgreSQL)或 JSON 文件中会是更好的选择。
基本思路:
这种方法允许按钮回调函数是无状态的,因为它总是从持久化存储中获取所需的数据。这对于构建可伸缩和容错的机器人非常有用。
以下是整合了上述修正和上下文传递机制的完整求婚系统示例:
import discord
from discord.ext import commands
# 初始化你的 Bot 客户端
# intents = discord.Intents.default()
# intents.members = True # 如果需要获取成员信息,请启用此意图
# client = commands.Bot(command_prefix='!', intents=intents)
# @client.event
# async def on_ready():
# print(f'Bot is ready. Logged in as {client.user}')
# await client.tree.sync() # 同步斜杠命令
class MarryButtons(discord.ui.View):
def __init__(self, proposer: discord.Member, target_user: discord.Member):
super().__init__(timeout=300) # 设置 View 的超时时间为 5 分钟 (300秒)
self.proposer = proposer
self.target_user = target_user
self.message = None # 用于存储原始消息,以便在超时时进行编辑
async def on_timeout(self):
if self.message:
embed = self.message.embeds[0]
embed.title = '求婚请求超时'
embed.description = f'{self.proposer.mention} 向 {self.target_user.mention} 的求婚请求已超时,未得到回应。'
embed.color = discord.Color.orange()
await self.message.edit(embed=embed, view=None) # 移除按钮
@discord.ui.button(label="接受求婚", style=discord.ButtonStyle.success)
async def agree_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 只有被求婚者才能点击此按钮
if interaction.user != self.target_user:
await interaction.response.send_message("你不是被求婚者,无法操作此按钮!", ephemeral=True)
return
embed_agree = discord.Embed(
title='恭喜!新婚快乐!',
description=f'{self.target_user.mention} 接受了 {self.proposer.mention} 的求婚!他们现在结婚了!?',
color=discord.Color.green()
)
# 编辑原始消息,移除按钮,并显示结果
await interaction.response.edit_message(embed=embed_agree, view=None)
self.stop() # 停止 View 监听,防止进一步交互
@discord.ui.button(label="拒绝求婚", style=discord.ButtonStyle.danger)
async def disagree_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 只有被求婚者才能点击此按钮
if interaction.user != self.target_user:
await interaction.response.send_message("你不是被求婚者,无法操作此按钮!", ephemeral=True)
return
embed_disagree = discord.Embed(
title='很遗憾',
description=f'{self.target_user.mention} 拒绝了 {self.proposer.mention} 的求婚。?',
color=discord.Color.red()
)
await interaction.response.edit_message(embed=embed_disagree, view=None)
self.stop()
@discord.ui.button(label="撤回求婚", style=discord.ButtonStyle.gray, emoji="↩️")
async def withdraw_btn(self, interaction: discord.Interaction, button: discord.ui.Button):
# 只有发起者才能撤回求婚
if interaction.user != self.proposer:
await interaction.response.send_message("你不是求婚发起者,无法撤回求婚。", ephemeral=True)
return
embed_withdraw = discord.Embed(
title='求婚已撤回',
description=f'{self.proposer.mention} 撤回了向 {self.target_user.mention} 的求婚提议。',
color=discord.Color.light_gray()
)
await interaction.response.edit_message(embed=embed_withdraw, view=None)
self.stop()
# 示例斜杠命令
# @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=user)
#
# embed_marry = discord.Embed(
# title='浪漫求婚进行中...',
# description=f'{interaction.user.mention} 正在向 {user.mention} 求婚!\n\n'
# f'请 {user.mention} 点击下方按钮回应。',
# color=0x774dea
# )
# # 发送消息并关联 View
# await interaction.response.send_message(embed=embed_marry, view=view)
# # 获取原始响应消息对象,并将其存储到 View 实例中,以便在 on_timeout 中访问
# view.message = await interaction.original_response()
# 如果是独立运行的脚本,需要添加 client.run('YOUR_BOT_TOKEN')
# client.run('YOUR_BOT_TOKEN')通过本教程,我们深入探讨了 Discord.py 中 discord.ui.Button 交互错误的常见原因——不正确的按钮回调函数签名。核心解决方案是确保回调函数只接受 self, interaction, button 这三个标准参数。为了在按钮回调中获取命令的上下文数据,我们推荐使用将数据作为 View 实例属性传递的方法,这既简单又高效。对于更复杂的应用场景,可以考虑持久化存储方案。遵循这些最佳实践,将有助于您构建稳定、健壮且用户友好的 Discord 机器人交互功能。
以上就是Discord.py 按钮交互错误:回调函数参数处理与上下文传递指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号