Discord.py:是否存在commands.check的按钮类比验证机制?
按钮验证的实现方案
Discord.py 没有内置像 commands.check 那样直接批量给按钮加验证的机制,但你完全不用手动给每个按钮处理函数重复写检查逻辑,有两种更高效的实现方式:
1. 自定义按钮检查装饰器
模仿 commands.check 的思路,自己封装一个装饰器,把白名单检查逻辑复用在任意按钮回调上:
首先调整检查函数的参数,适配按钮的交互对象(Interaction):
async def is_active(interaction): return interaction.guild.id in get_whitelist()
然后编写装饰器:
def check_button(check_func): def decorator(callback): async def wrapped(interaction, *args, **kwargs): # 先执行白名单检查 if not await check_func(interaction): await interaction.response.send_message("该服务器不在白名单中,无法使用此功能。", ephemeral=True) return # 检查通过才执行原按钮逻辑 await callback(interaction, *args, **kwargs) return wrapped return decorator
使用时直接给按钮回调加装饰器即可:
@check_button(is_active) async def my_button_callback(interaction): await interaction.response.send_message("按钮功能执行中...")
2. 基于视图(View)的全局检查
如果你的按钮都属于同一个视图,可以重写视图的 interaction_check 方法,实现该视图下所有按钮的统一验证:
import discord class WhitelistedView(discord.ui.View): async def interaction_check(self, interaction): # 白名单检查不通过时,发送提示并返回False阻止执行回调 if interaction.guild.id not in get_whitelist(): await interaction.response.send_message("该服务器不在白名单中,无法使用此功能。", ephemeral=True) return False # 检查通过返回True,继续执行按钮回调 return True # 使用示例:创建带验证的按钮视图 @bot.command() async def send_whitelisted_button(ctx): # 定义按钮回调 async def button_callback(interaction): await interaction.response.send_message("按钮功能执行中...") # 创建按钮并绑定回调 test_button = discord.ui.Button(label="测试按钮") test_button.callback = button_callback # 用自定义视图包裹按钮 view = WhitelistedView() view.add_item(test_button) await ctx.send("点击按钮测试", view=view)
这种方式下,WhitelistedView 里的所有按钮都会自动触发白名单检查,不用给每个按钮单独加装饰器。
内容的提问来源于stack exchange,提问作者Raffaello Banhammer
相关产品推荐
相关产品推荐

