Python 定时器/倒数计时与自定义持续时间?
这段代码是一个计时器,使用命令“!t90'开始 如何编写使用命令“”的选项!有多少秒 (或一个文件中的30、45、60、90、120(因为这些是我的服务器99.9%的时间使用的唯一计时器)) 谢谢Python 定时器/倒数计时与自定义持续时间?,python,timer,discord,discord.py,Python,Timer,Discord,Discord.py,这段代码是一个计时器,使用命令“!t90'开始 如何编写使用命令“”的选项!有多少秒 (或一个文件中的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
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秒,但它可能会等待更长时间。不过,它通常会非常接近 你应该修正你的缩进,很难说你的一些合作项目中有什么。一个选项是将秒数作为参数:async def t(ctx,seconds:int)
,然后将该数字传递给助手coroutine@PatrickHaugh感谢您的快速回复,我添加了async def t(ctx,seconds:int)
和seconds:int=[30,45,60,90120]
。这允许我使用列出的命令,但如何更改倒计时?因为它仍然会在每个命令上调用1:30