
在 discord.py 中,`discord.ui.view` 的 `interaction_check` 方法用于全局验证用户交互。本文将探讨当 `interaction_check` 逻辑过于严格时,如何导致部分按钮功能失效的问题。我们将通过优化 `interaction_check` 的实现,使其专注于通用权限验证,并将特定按钮的权限逻辑下放至各自的回调函数中,从而实现更灵活、健壮的按钮交互控制。
在 Discord 机器人开发中,discord.ui.View 和 discord.ui.Button 是构建富交互界面的核心组件。View 作为按钮、选择菜单等 UI 元素的容器,提供了一个便捷的机制来处理用户交互。其中,View 类中定义的 interaction_check 方法扮演着一个重要的角色,它允许开发者在任何按钮回调被触发之前,对用户的交互进行前置验证。如果 interaction_check 返回 False,则该交互将被阻止,任何按钮回调都不会执行。
开发者在使用 interaction_check 时,有时会遇到一个常见问题:当 interaction_check 的逻辑过于具体,包含了对特定按钮 custom_id 的检查时,可能会意外地阻止视图中其他按钮的正常功能。
考虑以下一个 MyView 类的示例,它包含一个 Acknowledge 按钮和一个 Revoke 按钮:
class MyView(discord.ui.View):
def __init__(self, user_id: str):
super().__init__()
self.user_id = user_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
# 原始的 interaction_check 逻辑
userid = int(self.user_id)
if interaction.user.id == userid and interaction.data["custom_id"] == "acknowledge":
return True
else:
await interaction.response.send_message("您无权使用此按钮。", ephemeral=True)
return False
@discord.ui.button(label="Acknowledge", emoji="<:check:1135773225423491122>", style=discord.ButtonStyle.grey, custom_id="acknowledge")
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
# Acknowledge 按钮的回调逻辑
new_embed = Embed.from_dict(interaction.message.embeds[0].to_dict())
new_embed.set_footer(text=f'Sent by {interaction.user.name} | Acknowledged: ✔')
await interaction.response.edit_message(embed=new_embed)
button.disabled = True
await interaction.message.edit(view=self)
@discord.ui.button(label="Revoke", emoji="<:Cross:1135773287880867900>", style=discord.ButtonStyle.grey, custom_id="revoke")
async def menu2(self, interaction: discord.Interaction, button: discord.ui.Button):
# Revoke 按钮的回调逻辑,包含其自身的角色检查
user = interaction.guild.get_member(interaction.user.id)
role1_id = 994233392478560297 # 示例角色ID
role2_id = 994233182532685825 # 示例角色ID
role1 = discord.utils.get(interaction.guild.roles, id=role1_id)
role2 = discord.utils.get(interaction.guild.roles, id=role2_id)
if role1 in user.roles or role2 in user.roles:
await interaction.channel.send(f"**惩罚已由 {interaction.user.mention} 撤销**")
await interaction.message.delete()
else:
await interaction.response.send_message("您没有使用此按钮所需的角色。", ephemeral=True)在这个例子中,interaction_check 方法不仅检查了交互用户的 ID 是否与视图绑定的 user_id 匹配,还额外检查了 interaction.data["custom_id"] == "acknowledge"。这意味着,只有当用户 ID 匹配并且点击的是 acknowledge 按钮时,interaction_check 才会返回 True。
问题在于,如果用户点击的是 revoke 按钮,即使其 user_id 匹配(或不匹配),interaction_check 中的 interaction.data["custom_id"] == "acknowledge" 条件也会导致整个检查失败。因此,revoke 按钮的回调方法 menu2 将永远无法被触发,即使它内部已经实现了针对特定角色的权限检查。这种设计导致了 interaction_check 过于“贪婪”,拦截了本应由按钮自身处理的交互。
解决此问题的关键在于明确 interaction_check 和单个按钮回调的职责。
根据这一原则,我们可以优化 interaction_check,使其不再包含对特定按钮 custom_id 的检查。
import discord
from discord import Embed, app_commands
from discord.app_commands import Choice
class MyView(discord.ui.View):
def __init__(self, user_id: str):
super().__init__()
self.user_id = user_id
async def interaction_check(self, interaction: discord.Interaction) -> bool:
"""
优化后的 interaction_check,仅检查交互用户是否为目标用户。
"""
userid = int(self.user_id)
# 仅检查用户ID是否匹配,不再限制特定按钮
if not (check := interaction.user.id == userid):
await interaction.response.send_message("您无权操作此交互。", ephemeral=True)
return check
@discord.ui.button(label="Acknowledge", emoji="<:check:1135773225423491122>", style=discord.ButtonStyle.grey, custom_id="acknowledge")
async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
"""
Acknowledge 按钮的回调,在 interaction_check 通过后执行。
"""
new_embed = Embed.from_dict(interaction.message.embeds[0].to_dict())
new_embed.set_footer(text=f'Sent by {interaction.user.name} | Acknowledged: ✔')
await interaction.response.edit_message(embed=new_embed)
button.disabled = True
await interaction.message.edit(view=self)
@discord.ui.button(label="Revoke", emoji="<:Cross:1135773287880867900>", style=discord.ButtonStyle.grey, custom_id="revoke")
async def menu2(self, interaction: discord.Interaction, button: discord.ui.Button):
"""
Revoke 按钮的回调,包含其自身的角色检查。
"""
user = interaction.guild.get_member(interaction.user.id)
# 示例角色ID,请替换为您的实际角色ID
headquarters_role_id = 994233392478560297
first_line_supervisors_role_id = 994233182532685825
role_headquarters = discord.utils.get(interaction.guild.roles, id=headquarters_role_id)
role_first_line = discord.utils.get(interaction.guild.roles, id=first_line_supervisors_role_id)
# 检查用户是否拥有所需角色
if (role_headquarters and role_headquarters in user.roles) or \
(role_first_line and role_first_line in user.roles):
await interaction.channel.send(f"**惩罚已由 {interaction.user.mention} 撤销**")
await interaction.message.delete()
else:
# 如果没有所需角色,则发送错误消息
await interaction.response.send_message("您没有使用此按钮所需的角色。", ephemeral=True)
# 假设 bot 实例已经初始化
# bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
# 示例斜杠命令,用于创建包含 MyView 的消息
# @bot.tree.command(name="infract")
# @app_commands.describe(userid = "User being infracted (ID only)")
# @app_commands.describe(reason = "Reason for infraction")
# @app_commands.describe(type = "Choose a type")
# @app_commands.choices(type=[
# Choice(name='Termination', value=1),
# Choice(name='Demotion', value=2),
# Choice(name='Infraction', value=3),
# Choice(name="Blacklist", value=4),
# Choice(name="Under Investigation", value=5)
# ])
# @app_commands.describe(note = "Any notes that should appear on the command response (put N/A if none)")
# @app_commands.describe(acknowledge = "Should there be an acknowledge button?")
# @app_commands.choices(acknowledge=[
# Choice(name='Yes', value=1),
# Choice(name='No', value=2)
# ])
# async def infract(interaction: discord.Interaction, userid: str, reason: str, type: Choice[int], note: str, acknowledge: Choice[int]):
# # 实际应用中,这里会创建并发送包含 MyView 的消息
# # 例如:
# # embed = discord.Embed(title="Infraction Report", description=f"User: <@{userid}>\nReason: {reason}")
# # view = MyView(user_id=userid)
# # await interaction.response.send_message(embed=embed, view=view)
# await interaction.response.send_message("Infraction command executed (for demonstration purposes).")
通过上述修改,interaction_check 现在只负责验证交互用户是否是 self.user_id 所代表的目标用户。如果通过,交互将继续传递给具体的按钮回调方法。此时,Revoke 按钮的 menu2 方法将能够执行其内部的角色检查逻辑,从而实现其预期的功能。
职责分离原则:
明确的错误反馈:
安全性考量:
合理设计 discord.ui.View 中的 interaction_check 方法对于构建健壮且用户友好的 Discord 机器人交互至关重要。通过将通用权限验证逻辑置于 interaction_check 中,并将特定按钮的权限逻辑下放至各自的回调方法,我们可以有效避免权限冲突,确保每个按钮都能按照预期工作,同时提供清晰的错误反馈,从而提升整体用户体验和代码的可维护性。这种分层权限管理的方法是处理复杂 UI 交互的有效策略。
以上就是优化 Discord.py UI 交互检查:实现灵活的按钮权限控制的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号