You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用discord.py编写不跨服务器生效的snipe指令

discord.py snipe指令跨服务器调取问题解决方案

核心解决思路是将全局单值存储改为按服务器ID分类的字典存储,仅需对原有代码做3处小修改:

  • 替换全局存储结构
    原有错误的全局存储写法通常为:
latest_deleted_msg = None

将其替换为以服务器ID为键的空字典:

snipe_store = {}
  • 修改消息删除事件的存储逻辑
    在on_message_delete监听事件中,按消息所属服务器ID写入对应存储位:
@bot.event
async def on_message_delete(message):
    # 过滤无所属服务器的私信等消息
    if not message.guild:
        return
    # 可按需存储需要的消息字段
    snipe_store[message.guild.id] = {
        "content": message.content,
        "author": message.author,
        "create_time": message.created_at
    }
  • 修改snipe指令的读取逻辑
    执行指令时仅读取当前触发服务器对应的存储记录:
@bot.command()
async def snipe(ctx):
    current_guild_record = snipe_store.get(ctx.guild.id)
    if not current_guild_record:
        await ctx.send("当前服务器暂无已删除消息记录")
        return
    # 原有消息展示逻辑保持不变即可
    await ctx.send(f"消息发送者:{current_guild_record['author'].display_name}\n消息内容:{current_guild_record['content']}")

如果需要进一步实现同服务器下跨频道隔离的效果,只需将存储的键替换为(服务器ID, 频道ID)的元组即可,整体逻辑无需调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:09:01