You need to enable JavaScript to run this app. discord.py 如何判断message.author是否为bot以过滤on_message_edit事件
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 如何判断message.author是否为bot以过滤on_message_edit事件

代码问题与修正方案

现有代码的失效原因

你当前写的bot判断逻辑无法生效的核心问题:

  • before是discord.py传入的Message实例,before.content是消息的纯文本字符串,字符串本身不存在author属性,原判断行if before.content.author == self.bot:不仅识别不了bot,甚至可能触发属性错误。
  • 消息的作者属性是直接挂载在Message对象上的,即before.author,而非content的附属属性。

两种可选择的过滤逻辑

根据你的实际需求选择对应判断条件:

  • 如果仅需要过滤当前自身bot的消息编辑日志(其他第三方bot、普通用户的编辑事件正常记录),替换原判断行即可:
    if before.author == self.bot.user: return
    这里self.bot.user是当前bot对应的用户对象,可精准匹配自身发的消息。
  • 如果需要过滤所有bot账号(含第三方bot)的消息编辑日志,直接读取用户对象自带的bot标识即可,无需逐个比对:
    if before.author.bot: return
    Discord会为所有认证的bot账号在User对象上自动赋值bot=True,普通用户该值为False。

优化后的完整代码

建议把过滤逻辑提前到数据库查询之前,减少无效的数据库IO请求:

@commands.Cog.listener()
async def on_message_edit(self, before, after):
    # 先做前置过滤,避免无效查询
    if before.author == self.bot.user:
        return
    # 可选:过滤私聊场景的消息编辑,避免后续取guild属性时报错
    if not before.guild:
        return
    
    channel1 = await self.bot.logs.find(before.guild.id)
    channel = channel1["channel"]
    logs = self.bot.get_channel(channel)
    
    if before.content != after.content:
        embed = discord.Embed(title="Message edited", color=0xe74c3c)
        embed.add_field(name="Previous message", value=f"{before.content}", inline=False)
        embed.add_field(name="New message", value=f"{after.content}", inline=False)
        await logs.send(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.01 09:27:04