You need to enable JavaScript to run this app. 如何让Discord Bot的snipe命令支持抓取被删除的图片消息?
优惠活动
大模型
产品
解决方案
定价
更多

如何让Discord Bot的snipe命令支持抓取被删除的图片消息?

Discord Bot snipe 命令支持图片抓取的实现方案

现有代码的问题根源

该功能完全可以扩展实现图片snipe,当前功能失效的核心原因有两个:

  • 存储被删除消息时,没有抓取消息附带的附件(图片、文件)字段,碰到纯无文字的图片消息时,存储的message.content为空,生成的嵌入自然没有有效信息
  • 仅用guild.id作为存储字典的键,同个服务器下不同频道的删除消息会互相覆盖,跨频道触发snipe时很容易取到空内容

修正后的完整可运行代码

bot.sniped_messages = {}
  
@bot.event
async def on_message_delete(message):
  # 采用(服务器ID, 频道ID)组合键,避免同服务器跨频道的消息互相覆盖
  storage_key = (message.guild.id, message.channel.id)
  # 存储时额外保留消息的附件列表字段
  bot.sniped_messages[storage_key] = (
      message.content, 
      message.author, 
      message.channel.name, 
      message.created_at,
      message.attachments
  )
    
@bot.command()
async def snipe(ctx):
  storage_key = (ctx.guild.id, ctx.channel.id)
  try:
    content, author, channel_name, delete_time, attachments = bot.sniped_messages[storage_key]
        
  except KeyError:
    await ctx.channel.send("Nemohu najít zprávu na snipenutí.")
    return
  # 处理纯图片无文字的场景,给嵌入增加占位提示,避免描述为空
  display_text = content if content else "*(该被删除消息无文字内容)*"
  embed = discord.Embed(
      description=display_text,
      color=ctx.author.color,
      timestamp=delete_time
  )
  embed.set_author(
      name=f"{author.name}#{author.discriminator}", 
      icon_url=author.avatar_url
  )
  # 处理附件逻辑
  if attachments:
      first_attach = attachments[0]
      # 识别图片类型附件,直接设置为嵌入的展示大图
      if "image" in first_attach.content_type:
          embed.set_image(url=first_attach.url)
      else:
          # 识别非图片的普通附件,在描述里附带上下载链接
          embed.description += f"\n\n📎 附带附件:[{first_attach.filename}]({first_attach.url})"
  embed.set_footer(text=f"Smazáno v #{channel_name}")
    
  await ctx.send(embed=embed)

额外优化提示

  • 原代码使用裸except捕获所有异常,会把代码运行时的其他bug误判为“找不到可snipe的消息”,改为捕获KeyError能大幅提高代码健壮性
  • 当前实现仅保留每个频道最近1条被删除的消息,如果需要支持多位置snipe,可以把存储结构改成按频道存列表,保留最近N条被删除消息即可
  • Discord CDN的附件链接为临时有效链接,在消息删除后及时触发snipe即可正常展示图片,无需额外做文件转存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.08 09:06:01