首页 > 解决方案 > 使用 datetime 作为存储在 JSON 中的计时器

问题描述

我正在尝试datetime从 JSON 中的存储datetime值中减去,以查看是否已经过了 2 分钟才能再次使用命令。当我使用该命令时,每次 JSON 值更新为“0”时,即使我打印currentime它也会给我想要存储的值。我已经尝试更改timer[id]["flytimer"] = (datetime.datetime.utcnow() - epoch).total_seconds()timer[id]["flytimer"] = 0但仍然得到相同的结果

try:
    with open("timer.json") as fp:
        timer = json.load(fp)
except Exception:
    timer = {}

def save_timer():
    with open("timer.json", "w+") as fp:
        json.dump(timer, fp, sort_keys=True, indent=4)

def add_flytimer(user: discord.User, flytimer: int):
    id = user.id
    if id not in timer:
        timer[id] = {}
        timer[id]["flytimer"] = (datetime.datetime.utcnow() - epoch).total_seconds()
        save_timer()

def get_flytimer(user: discord.User):
    id = user.id
    if id in timer:
        return timer[id].get("flytimer", 0)
    return 0

def reset_flytimer(user: discord.User, flytimer: int):
    id = user.id
    if id in timer:
        timer[id]["flytimer"] = 0
        print("{} flight timer reset".format(user.name))
        save_timer()


            epoch = datetime.datetime.utcfromtimestamp(0)
            currenttime = (datetime.datetime.utcnow() - epoch).total_seconds()
            if message.content.startswith('!flight'):
                print(currenttime)
                if get_flytimer is None:
                    add_flytimer(message.author, currenttime)
                    print(currenttime)
                    print(get_flytimer(message.author))
                    await client.send_message(message.channel, "{} takes a flight to NY".format(message.author))
                else:
                    takeflight = currenttime - get_flytimer(message.author)
                    if takeflight >= 120:
                        add_flytimer(message.author,currenttime)
                        print(get_flytimer(message.author))
                        await client.send_message(message.channel, "{} takes a flight to NY".format(message.author))
                    else:
                        await client.send_message(message.channel, "{} you still have {} seconds until the next flight".format(message.author, takeflight))

标签: pythonpython-3.xdiscorddiscord.py

解决方案


推荐阅读