Discord.py机器人开发咨询:已实现删除消息snipe,如何开发编辑snipe命令
对齐现有架构实现编辑snipe功能
复用你当前删除snipe的全局变量存储、Cog事件监听、固定频道日志上报的整套逻辑,仅需要新增对接discord.py内置的on_message_edit事件,完全不改动原有删除snipe的运行逻辑。
核心实现逻辑
- 新增独立命名的全局变量,和删除snipe的变量做区分,避免编辑、删除消息的存储值互相覆盖:
- 存储编辑前原始文本的
edit_snipe_old_content - 存储编辑后最新文本的
edit_snipe_new_content - 存储编辑消息作者ID的
edit_snipe_author_id - 存储编辑消息所属频道的
edit_snipe_channel - 配套存储作者头像、用户名、身份标识的变量
- 存储编辑前原始文本的
- 新增Cog监听方法绑定
on_message_edit事件,该事件会自动传入两个参数:编辑前的原始消息对象before、编辑后的最新消息对象after - 沿用原有过滤规则:如果编辑消息的作者在
botsid机器人屏蔽列表内,直接跳过后续存储,不记录机器人发送的消息 - 增加无效编辑过滤:如果
before.content和after.content完全一致(比如仅更新附件、刷新embed触发的编辑回调),直接跳过,不占用snipe存储位 - 沿用现有embed格式做展示,将删除对应的标识替换为编辑专属标识,在embed中区分展示编辑前、编辑后的内容
适配现有代码的参考实现
# 全局变量定义在类外,和原有删除snipe的全局变量放在同一作用域 edit_snipe_old_content = None edit_snipe_new_content = None edit_snipe_author_id = None edit_snipe_channel = None edit_snipe_author_avatar = None edit_snipe_author_name = None edit_snipe_author_discriminator = None # 新增监听器,和原有on_message_delete方法放在同一个Cog类中 @commands.Cog.listener() async def on_message_edit(self, before, after): global edit_snipe_old_content global edit_snipe_new_content global edit_snipe_author_id global edit_snipe_channel global edit_snipe_author_avatar global edit_snipe_author_name global edit_snipe_author_discriminator # 过滤机器人消息、无文本变化的无效编辑 if after.author.id in botsid or before.content == after.content: return # 赋值存储对应消息字段 edit_snipe_old_content = before.content edit_snipe_new_content = after.content edit_snipe_author_id = after.author.id edit_snipe_channel = after.channel edit_snipe_author_avatar = after.author.avatar_url edit_snipe_author_name = after.author.name edit_snipe_author_discriminator = after.author.discriminator # 沿用现有固定频道上报的embed格式 embed = discord.Embed( description=( f"✏️ **Message sent by** <@!{edit_snipe_author_id}> **edited in** {after.channel.mention}\n\n" f"**Before:**\n{edit_snipe_old_content}\n\n" f"**After:**\n{edit_snipe_new_content}" ) ) embed.set_author( name=f" {edit_snipe_author_name}#{edit_snipe_author_discriminator}" ) # 复用原有的日志频道ID log_channel = self.client.get_channel(795726497922809947) await log_channel.send(embed=embed)
原有删除snipe代码中的
if (snipe_message_author in botsid): m == 1逻辑无实际拦截效果,编辑snipe的实现中已修正为直接return跳过,不会记录机器人消息。
内容的提问来源于stack exchange,提问作者Mohd osama
相关产品推荐
相关产品推荐

