簡體   English   中英

具有自定義持續時間的計時器/倒計時?

[英]Timer/countdown with custom duration?

這部分代碼是一個計時器,設置了90秒的持續時間,使用命令“!t90”啟動。

如何編寫使用命令“!t”的秒數的選項?

(或在一個文件中分別包含30、45、60、90、120(因為這些是我的服務器將使用99.9%的時間的唯一計時器))

謝謝

import discord
from discord.ext import commands
  import asyncio

bot = commands.Bot(command_prefix="!")
counter_channel = None
task = None

async def ex(message):

global counter_channel
if counter_channel is not None:
    await bot.send_message(
        message.channel,
        embed=discord.Embed("There is a counter in {}".format(counter_channel.mention), color=discord.Color.red() ))
    return

counter_channel = message.channel
await bot.send_message(message.channel, "1:30")
await asyncio.sleep(30)
await bot.send_message(message.channel, "1:00")
await asyncio.sleep(30)
await bot.send_message(message.channel, "0:30")
await asyncio.sleep(20)
await bot.send_message(message.channel, "0:10")
await asyncio.sleep(10)
await bot.send_message(message.channel, "time")
counter_channel = None

@bot.command(pass_context=True)
async def t90(ctx):
global task
task = bot.loop.create_task(ex(ctx.message))

@bot.command(pass_context=True)
async def cancel(ctx):
global task, counter_channel
await bot.send_message(message.channel, "timer reset")
task.cancel()
task = None
counter_channel = None


bot.run('###token###')

這是您可以執行此命令的一種方法

from datetime import timedelta
from asyncio import sleep

def time_repr(td: timedelta) -> str:
    "Time formatter with optional dates/hours"
    minutes, seconds = divmod(int(td.total_seconds()), 60)
    hours, minutes = divmod(minutes, 60)
    days , hours = divmod(hours, 24)
    res = f"{minutes:>02}:{seconds:>02}"
    if hours or days:
        res = f"{hours:>02}:" + res
    if days:
        res =  f"{td.days} days, " + res
    return res

@bot.command(pass_context=True)
async def countdown(ctx, seconds: int):
    td = timedelta(seconds=seconds)
    while True:
        await bot.say(time_repr(td))
        if td.total_seconds() > 30:
            td -= timedelta(seconds=30)
            await sleep(30)
        elif td.total_seconds > 10:
            td -= timedelta(seconds=10)
            await sleep(10)
        elif td.total_seconds > 1:
            td -= timedelta(seconds=1)
            await sleep(1)
        else:
            break

注意,這並不總是最好的計時器: sleep(10)保證事件循環至少等待10秒,但它可能等待更長的時間。 通常它會很接近。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM