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

discord.py开发:JSON新增内容仅推最新条目问题排查

解决Discord机器人推送JSON所有条目而非新增条目的问题

你的核心问题有两个:一是tasks.loop内部嵌套while True导致循环逻辑冲突,且初始化的last_length每次循环都会重置;二是检测到文件更新后直接遍历所有条目,没有筛选新增内容。

修正方案

我们可以通过保存已推送过的条目键集合来区分新增内容,同时梳理循环逻辑,利用定时机制的原生功能:

@tasks.loop(seconds=20)
async def update():
    global sent_keys
    # 首次启动时读取现有JSON的键,作为已推送过的集合
    try:
        with open('Game Bot/games.json', 'r') as f:
            config_data = json.load(f)
        sent_keys = set(config_data.keys())
    except (FileNotFoundError, json.JSONDecodeError):
        sent_keys = set()

    last_modified = os.path.getmtime('Game Bot/games.json')
    
    while True:
        await asyncio.sleep(20)
        current_modified = os.path.getmtime('Game Bot/games.json')
        if current_modified != last_modified:
            last_modified = current_modified
            with open('Game Bot/games.json', 'r') as f:
                config_data = json.load(f)
            
            current_keys = set(config_data.keys())
            # 计算新增条目:当前键集合减去已推送的键集合
            new_keys = current_keys - sent_keys
            
            if new_keys:
                channel = bot.get_channel(1090051943633780758)
                for key in new_keys:
                    embed = discord.Embed(title="New Game Added!", color=0xFFFFFF)
                    embed.add_field(name=key, value=f"[Download]({config_data[key]})")
                    await channel.send(embed=embed)
                print("New games pushed.")
                # 更新已推送的键集合
                sent_keys.update(new_keys)

关键改动说明

  1. 用键集合替代长度判断:通过对比current_keys和sent_keys,精准筛选出新增条目,避免仅靠长度变化无法定位具体新增内容的问题,同时也能排除条目修改导致的误推送。
  2. 修复循环逻辑:初始化时先同步现有JSON的已推送状态,后续每次检测到文件更新时,只处理新增的键,推送完成后更新sent_keys。
  3. 简化嵌套结构:保留内部while True配合asyncio.sleep控制检测间隔,避免和tasks.loop的定时功能冲突,逻辑更清晰。

额外注意事项

  • 确保sent_keys为全局变量或类属性,防止每次循环重置导致状态丢失。
  • 增加文件读取的异常处理,避免JSON文件损坏或不存在时机器人崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:22:56