【问题标题】:Timer/countdown with custom duration?具有自定义持续时间的计时器/倒计时?
【发布时间】:2019-02-06 02:33:43
【问题描述】:

这段代码是一个设置持续时间为 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###')

【问题讨论】:

  • 你应该修复你的缩进,很难说出你的一些协程中有什么。一种选择是将秒数作为参数:async def t(ctx, seconds: int),然后将该数字传递给您的辅助协程
  • @PatrickHaugh 感谢您的快速回复,我添加了async def t(ctx, seconds: int)seconds:int = [30,45,60,90,120]。这允许我使用列出的命令,但如何更改倒计时 - 因为它仍然在每个命令上调用 1:30

标签: python timer discord discord.py


【解决方案1】:

这是你可以发出这样一个命令的一种方法

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 秒,但它可能会等待更长时间。不过,它通常会非常接近。

【讨论】:

    猜你喜欢
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多