这段代码是一个计时器,设置了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###')
答案 0 :(得分:0)
这是您发出这样的命令的一种方式
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秒,但可能会等待更长的时间。通常它会很接近。