Discord.py消息删除日志开发:如何识别消息删除操作人
Discord机器人消息删除日志功能问题修复
问题分析
你的代码存在以下核心问题,导致逻辑失效和误判:
- 审计日志条目匹配错误:仅取最新1条审计日志,短时间内多个删除操作时,会错误匹配到其他删除事件的条目
- 时间匹配精度不足:用
%d-%m-%Y %H:%M做时间比对,同一分钟内的多个操作会被误判为同一事件 - 变量未初始化:
not_self_delete无默认值,若审计日志查询失败(比如机器人无查看权限)会引发未定义错误 - 变量名错误:存在
localtime、deleter、embed2等未定义或错误的变量引用 - 逻辑判断顺序错误:默认假设是他人删除,应先默认自删,再通过审计日志验证是否为他人操作
修复后的代码
import datetime from datetime import timezone import discord from discord.ext import commands @commands.Cog.listener() async def on_message_delete(self, message: discord.Message): # 跳过私信频道 if message.channel.type == discord.ChannelType.private: return # 仅处理目标服务器的消息 if not hasattr(message.author, "guild") or message.guild.id != IEEM: return # 跳过机器人消息 if message.author.bot: return not_self_delete = False deleted_by = None current_time = datetime.datetime.now(timezone.utc) # 查询最近5条消息删除审计日志,提高匹配概率 async for entry in message.guild.audit_logs(limit=5, action=discord.AuditLogAction.message_delete): # 10秒内的条目视为与当前删除事件相关 time_diff = (current_time - entry.created_at).total_seconds() if abs(time_diff) <= 10: # 兼容单条删除(target为作者)和批量删除(extra.channel为消息频道)场景 if entry.target == message.author or (hasattr(entry.extra, 'channel') and entry.extra.channel == message.channel): deleted_by = entry.user if deleted_by != message.author: not_self_delete = True break # 构建日志Embed embed = discord.Embed( title=f"{message.author.name} 删除了一条消息", description=f"内容: {message.content or '[无文本内容]'} \n 频道: {message.channel.mention}", color=0xFF5733 ) embed.set_author(name=self.bot.user.name, icon_url=self.bot.user.display_avatar) # 设置底部文本 delete_time = current_time.strftime("%d-%m-%Y %H:%M") if not_self_delete and deleted_by: embed.set_footer(text=f"消息删除时间: {delete_time} \n 删除操作者: {deleted_by.name}") else: embed.set_footer(text=f"消息删除时间: {delete_time}") # 处理附件 attachment_files = [] for index, attach in enumerate(message.attachments): embed.add_field(name=f"附件 {index+1}", value=f"[{attach.filename}]({attach.url})") attachment_file = await attach.to_file() attachment_files.append(attachment_file) # 发送日志到目标频道 channel1 = self.bot.get_channel(my_log_chan) channel2 = self.bot.get_channel(another_log_chan_in_diff_server) if channel1: await channel1.send(embed=embed, files=attachment_files) if channel2: await channel2.send(embed=embed, files=attachment_files)
关键修复点说明
- 扩大审计日志查询范围:查询最近5条条目,避免短时间多操作时匹配错误
- 精确时间匹配:用10秒时间差替代分钟级比对,提高事件匹配准确性
- 完善目标匹配逻辑:同时匹配消息作者和频道,兼容单条删除和批量删除场景
- 变量初始化:提前设置
not_self_delete默认值为False,避免未定义错误 - 修正变量名错误:统一变量命名,修复
embed2、localtime等错误引用 - 优化流程顺序:先过滤不需要处理的场景(私信、非目标服务器、机器人消息),减少无效执行
内容的提问来源于stack exchange,提问作者Ernedhir
相关产品推荐
相关产品推荐

