我正在使用discord.py制作一个Discorde机器人,并且有一个很好的小设置,所以当我向我的json文件添加一些东西时,它每隔20秒判断一次,如果有什么改变了,它将发送一个嵌入了新内容的Discorde.唯一的问题是,它不是发送最新的行,而是发送每一行(所有内容中的行)

以下是代码:

@tasks.loop(seconds=10)
async def update():
    print("Games Update Loop Started")
    last_modified = os.path.getmtime('Game Bot/games.json')
    last_length = 0  # initialize the last length of the JSON file
    while True:
        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)
            if len(config_data) > last_length:  # check if new line(s) have been added
                for key, value in config_data.items():
                    embed = discord.Embed(title="New Game Added!", color=0xFFFFFF)
                    embed.add_field(name=key, value=f"[Download]({value})")
                    channel = bot.get_channel(1090051943633780758)
                    await channel.send(embed=embed)
                print("Games updated.")
                last_length = len(config_data)  # update the last length of the JSON file
        await asyncio.sleep(10)

这是我的.json文件

{
    "Sons Of The Forest [MULTIPLAYER]" : "https://youtube.com/watch?v=dQw4w9WgXcQ",
    "Geometry Dash [FULL VERSION]" : "https://youtube.com/watch?v=dQw4w9WgX",
    "Rust [MULTIPLAYER]" : "https://youtube.com/watch?v=dQw4w"
}

我几乎try 了我能想到的所有东西(基本上没有什么是因为我很傻),并希望它只发送最新的内容行.它发出了非常丰富的内容.

推荐答案

您的JSON文件的格式似乎不正确,请将您的数据放入列表并添加键以使其更容易排序.将您的JSON文件重新格式化为类似以下内容.

{
  "videos": [
    {
      "title": "Sons Of The Forest [MULTIPLAYER]", "link": "https://youtube.com/watch?v=dQw4w9WgXcQ"
    },
    { "title": "Geometry Dash [FULL VERSION]", "link":  "https://youtube.com/watch?v=dQw4w9WgX" },
    { "title": "Rust [MULTIPLAYER]", "link":  "https://youtube.com/watch?v=dQw4w" }
  ]

所有对象都放在一个列表中,这意味着您可以对它们进行索引和排序.在此之前,您需要密钥才能访问对象.这意味着,如果您希望明确返回对象的标题,则需要该对象的标题.例如,您需要按键"Sons Of The Forest [MULTIPLAYER]"才能返回"https://youtube.com/watch?v=dQw4w9WgXcQ".否则,你只需要仔细判断每一个物体,就能得到你正在寻找的那个物体,这就是你的错误.

有了列表,要获得最新添加的内容,您需要做的就是为最后一项建立索引.使用更新的JSON,您可以执行config_data['videos']个操作来获得列表.然后,您可以对其使用您的len函数.要收听最新的"专线",请拨打config_data['videos][-1].-1访问列表中的最后一项.

一旦每个对象都在列表中,您就可以添加键来访问值,如标题或链接.这意味着如果您想要某个值,您可以从列表中对其进行索引,并通过括号访问您想要的值.因此,要返回最新行的标题,您需要返回config_data['videos'][-1]['title].

所有的方括号都有点混乱,所以您应该先将其中一些放在变量中.以下是一些更新的代码,其中的逻辑已更改为与JSON一起使用.


@tasks.loop(seconds=10)
async def update():
    print("Games Update Loop Started")
    last_modified = os.path.getmtime('Game Bot/games.json')
    last_length = 0
    while True:
        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)
                videos = config_data['videos'] # Getting list

            if len(videos) > last_length: 
                    newest_video = videos[-1] # Getting last item in list
                    
                    title = newest_video['title']
                    link = newest_video['link'] # Accessing link of object

                    embed = discord.Embed(
                        title="New Game Added!", color=0xFFFFFF)
                    embed.add_field(name=title, value=f"[Download]({link})")
                    channel = bot.get_channel(1090051943633780758)
                    await channel.send(embed=embed)
                print("Games updated.")
                last_length = len(videos)
        await asyncio.sleep(10)

Python相关问答推荐

调查TensorFlow和PyTorch性能的差异

查找3D数组中沿一个轴的相同值序列的长度(与行程长度编码相关)

使用pandas MultiIndex进行不连续 Select

将numpy矩阵映射到字符串矩阵

剧作家Python没有得到回应

如何根据另一列值用字典中的值替换列值

rame中不兼容的d类型

带条件计算最小值

使用索引列表列表对列进行切片并获取行方向的向量长度

输出中带有南的亚麻神经网络

如何使用它?

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

多指标不同顺序串联大Pandas 模型

什么是最好的方法来切割一个相框到一个面具的第一个实例?

多处理队列在与Forking http.server一起使用时随机跳过项目

如何在turtle中不使用write()来绘制填充字母(例如OEG)

python中的解释会在后台调用函数吗?

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

如何杀死一个进程,我的Python可执行文件以sudo启动?

搜索按钮不工作,Python tkinter