Discord编辑消息狙击(snipe)功能失效 代码运行异常求助
问题排查与修复方案
- 作用域错误:全局定义的
snipe_message_author是字典结构,你在on_message_edit事件内直接赋值为用户对象,实际是创建了事件函数内的局部变量,完全没有修改全局字典,也没有按频道ID存储对应的数据。 - 变量访问错误:
message_before、message_after是on_message_edit事件的局部参数,snipeedit命令函数无法直接访问这两个变量,调用时必然抛出异常触发except分支。 - 存储逻辑错误:你没有按频道维度存储编辑前后的消息内容、作者等信息,即使解决作用域问题也无法对应到当前调用命令的频道的编辑记录。
修复后的代码
# 全局字典按频道ID存储编辑消息记录,结构:{频道ID: {"author": 作者对象, "before": 原消息内容, "after": 编辑后内容}} snipe_store = {} @client.event async def on_message_edit(message_before, message_after): # 忽略机器人自身的消息编辑 if message_before.author.bot: return # 声明要修改全局变量 global snipe_store # 按频道ID存储对应编辑记录 snipe_store[message_before.channel.id] = { "author": message_before.author, "before": message_before.content, "after": message_after.content } @client.command() async def snipeedit(ctx): channel = ctx.channel try: # 从全局存储中取出当前频道的编辑记录 record = snipe_store[channel.id] snipeEmbed = discord.Embed( colour = discord.Colour.orange(), title = f"{record['author']}", description = f"""Original message : {record['before']} Updated message : {record['after']}""" ) await ctx.send(embed = snipeEmbed) except KeyError: # 只捕获找不到记录的异常,避免隐藏其他报错 await ctx.send(f"There are no edited messages in #{channel.name}")
额外优化建议
- 建议只捕获
KeyError异常而不是所有异常,避免其他代码错误被隐藏无法排查。 - 增加忽略机器人消息编辑的逻辑,避免狙击到机器人的自动编辑消息。
- 如果需要支持存储多条编辑记录,可以将字典对应的值改为列表结构存储历史记录。
内容的提问来源于stack exchange,提问作者user16186190
相关产品推荐
相关产品推荐

