You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py:如何在check的谓词函数中访问self?

解决方案

直接在校验函数(predicate)中通过ctx.cog访问Cog实例,就能调用实例内的数据获取方法完成校验。

完整示例代码

def custom_check():
    async def predicate(ctx):
        # 通过ctx.cog获取当前命令所属的Cog实例
        cog_instance = ctx.cog
        # 调用Cog实例的方法进行数据获取
        data = await cog_instance.some_data_fetching()
        # 这里编写你的校验逻辑,根据数据返回True/False
        return data is not None

    return commands.check(predicate)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    @custom_check()
    async def func(self, ctx):
        await ctx.send("校验通过!")

    async def some_data_fetching(self):
        # 模拟数据获取逻辑
        return "示例数据"

你的尝试失效原因

  1. 嵌套装饰器的逻辑错误:commands.check需要直接作用于命令函数,你额外套的wrapper没有被纳入Discord.py的校验流程,导致predicate根本没被触发。
  2. 没必要手动注入self:Discord.py会自动把命令所属的Cog实例绑定到ctx.cog属性上,不需要通过包装函数传递。

额外优化

如果这个校验只针对特定Cog,可以在predicate里加类型判断,避免其他Cog误用:

async def predicate(ctx):
    if not isinstance(ctx.cog, MyCog):
        return False
    # 后续校验逻辑...

内容的提问来源于stack exchange,提问作者Daniel Baulig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 03:22:40