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

Discord.py中如何利用cog_check阻止机器人响应自身/其他机器人?

解决Discord机器人不响应自身/其他机器人的问题

cog_check 仅对**命令(Command)**生效,监听器(Listener)需要单独处理。下面是完整的实现方案:

一、用cog_check过滤所有命令

在你的Cog类里定义cog_check方法,类内所有命令都会自动执行这个校验:

from discord.ext import commands
import discord

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

    # 全局命令检查:发送者是机器人就返回False,阻止命令执行
    async def cog_check(self, ctx):
        return not ctx.author.bot

    # 示例命令,会自动应用上面的检查
    @commands.command()
    async def greet(self, ctx):
        await ctx.send(f"哈喽,{ctx.author.name}!")

二、给监听器添加机器人过滤

cog_check管不到监听器,你可以选两种方式处理:

方式1:用装饰器统一过滤

写个简单的装饰器,给需要的监听器套用即可,减少重复代码:

def skip_bots(func):
    async def wrapper(self, message, *args, **kwargs):
        if message.author.bot:
            return  # 是机器人就直接返回,不执行后续逻辑
        await func(self, message, *args, **kwargs)
    return wrapper

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

    # 保留上面的cog_check处理命令

    # 给监听器加上装饰器
    @commands.Cog.listener()
    @skip_bots
    async def on_message(self, message):
        # 只有非机器人发送的消息才会执行到这里
        await message.channel.send(f"收到内容:{message.content}")

方式2:直接在监听器内加判断

不想写装饰器的话,直接在监听器开头加判断逻辑就行:

@commands.Cog.listener()
async def on_message(self, message):
    if message.author.bot:
        return
    # 这里写你的业务逻辑

关键提示

  • ctx.author.bot(命令场景)和message.author.bot(监听器场景)会自动识别所有机器人账号,包括你自己的机器人,无需额外写判断自身的逻辑。
  • 要是使用on_message监听器,记得在机器人初始化时开启messages意图:
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix="!", intents=intents)

内容的提问来源于stack exchange,提问作者1FattyGoldfish

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:16:11