显示asyncio.sleep的剩余时间

时间:2018-07-02 07:01:05

标签: python time python-asyncio

我有以下命令:

if message.content.lower().startswith("!activate"):
    if message.author.id not in tempo:
        await Bot.send_message(message.channel, "{} used the command".format(message.author.name))
        tempo.append(message.author.id)
        await asyncio.sleep(720)
        tempo.remove(message.author.id)
    else:
        await Bot.send_message(message.channel, "wait {} hours.".format(asyncio.sleep))

我希望该人员每次尝试使用该命令时,都要显示还剩下多少时间才能再次使用它,例如:“等待4小时50分钟。”

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以只存储时间并自己计算剩余时间:

import time
tempo = {} # use a dict to store the time

if message.content.lower().startswith("!activate"):
    if message.author.id not in tempo:
        await Bot.send_message(message.channel, "{} used the command".format(
            message.author.name))
        tempo[message.author.id] = time.time() + 720 # store end time
        await asyncio.sleep(720)
        del tempo[message.author.id]
    else:
        await Bot.send_message(message.channel, "wait {} seconds.".format(
            tempo[message.author.id] - time.time()))