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

如何让Discord机器人忽略指定角色的消息编辑日志?

修改Discord机器人on_message_edit事件,忽略指定角色的编辑日志

问题背景

现有on_message_edit事件代码实现以下逻辑:

  • 消息被编辑时,记录编辑前后内容到日志频道
  • 若编辑后消息包含Discord邀请链接,无权限角色的消息会被删除、记录日志并私信警告
  • 已配置allowed_roles变量允许部分角色发送邀请链接,但这些角色编辑消息时仍会触发日志记录,需要修改为完全忽略指定角色的所有编辑操作,不触发任何日志

修改后的代码

@client.event # Edited message logs
async def on_message_edit(before, after):
    author = after.author
    # 先检查是否为允许的角色,是则直接返回,忽略所有后续逻辑
    has_allowed_role = any(role.id in allowed_roles for role in author.roles)
    if has_allowed_role:
        return
    
    if "discord.gg" in after.content or "https://discord.gg/" in after.content or "discord.gg/" in after.content:
        await after.delete()
        embed = discord.Embed(title="Message Deleted", description=f"A message from {author.mention} contained an invite link after editing and was deleted.\n\nOriginal message:\n{before.content}\nEdited message: \n{after.content}", color=discord.Color.red())
        embed.set_footer(text=footer_text, icon_url=footer_url)
        await client.get_channel(log_channel).send(embed=embed)
        dm = await after.author.create_dm()
        embed = discord.Embed(title="Warning", description=f"Advertising is not allowed in our server. Your message after editing has been deleted and a proof has been sent to the log channel.\n\nYour message:\n{after.content}", color=discord.Color.red())
        embed.set_footer(text=footer_text, icon_url=footer_url)
        await dm.send(embed=embed)
    else:
        embed = discord.Embed(title="Message Edited", description=f"Original message sent by {author.mention}:\n{before.content}\nEdited message:\n{after.content}", color=discord.Color.red())
        embed.set_footer(text=footer_text, icon_url=footer_url)
        await client.get_channel(log_channel).send(embed=embed)

修改说明

  • 提前判断角色权限:在函数最开头添加角色检查逻辑,用any()简化原有的循环判断,更简洁高效
  • 直接终止逻辑:如果用户属于allowed_roles中的任意角色,直接return跳出函数,不执行后续的日志记录和链接检测逻辑
  • 彻底忽略操作:原代码中允许角色的编辑仍会触发日志,现在完全跳过所有后续操作,实现对指定角色编辑行为的无感知处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 16:32:33