discord.py使用cogs实现Snipe撤回消息查看功能运行异常求助
Discord.py Snipe Cog 故障修复方案
核心问题点
on_message_delete事件未添加@commands.Cog.listener()装饰器,框架不会触发该回调,删除消息的存储逻辑从未执行- 存储删除消息的字典被定义为
on_message_delete的局部变量,每次事件执行都会重置为空,且执行结束后变量直接销毁,数据无法留存供命令读取 snipe命令错误尝试从ctx对象读取不存在的messagecontent属性,必然抛出异常进入错误分支
修复后完整代码
import discord from discord.ext import commands class Snipe(commands.Cog): def __init__(self, client): self.client = client # 初始化类实例属性存储删除消息数据,全局生效 self.snipe_author = {} self.snipe_content = {} @commands.Cog.listener() async def on_ready(self): print("Snipe is now enabled") # 添加事件监听装饰器 @commands.Cog.listener() async def on_message_delete(self, message): # 数据存入实例属性,不会被销毁 self.snipe_author[message.channel.id] = message.author self.snipe_content[message.channel.id] = message.content @commands.command() async def snipe(self, ctx): channel = ctx.channel try: # 从实例属性读取存储的消息数据 author = self.snipe_author[channel.id] content = self.snipe_content[channel.id] em = discord.Embed(description = f"{author.mention} said:\n{content}", color = 0x00c230) em.set_author(name = f"Last deleted message in #{ctx.channel.name}") em.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096") em.set_footer(text = f"Snipe requested by {ctx.message.author}") await ctx.send(embed = em) except KeyError: embed = discord.Embed(colour = 0x00c230) embed.set_author(name=f"There are no deleted messages in #{ctx.channel.name}!") embed.set_thumbnail(url="https://cdn.discordapp.com/avatars/352793093105254402/8a2018de21ad29973696bfbf92fc31cd.png?size=4096") embed.set_footer(text=f"Snipe requested by {ctx.message.author}") await ctx.send(embed=embed) def setup(client): client.add_cog(Snipe(client))
附加优化说明
- 把原来的裸
except改为捕获KeyError,避免吞掉其他未知异常方便后续排查 - 消息内容展示补充了发送者@提醒,信息更完整
内容的提问来源于stack exchange,提问作者53x2
相关产品推荐
相关产品推荐

