【发布时间】:2023-03-22 04:26:01
【问题描述】:
我想在 Discord.py 中循环一个任务,该任务将在不同时间循环几个不同的公会。例如,如果一个公会在 20:00 调用此命令,而另一个公会在 13:00 调用该命令,我希望能够在每个公会每天的同一时间(在他们指定的时间)运行该命令。我还希望在维护后重新启动服务器时重新加载这些命令。
所以,基本上,我希望每个服务器每天在不同时间运行某个命令。我还希望保存计时器,以便在服务器重新启动后它们在那里。
我现在这样做的方法是拥有一个外部数据库,该数据库存储运行命令所需的所有必要信息,在启动时加载该信息,并在启动时调用异步命令,基本上重新加载所有保存的计时器。
这是我到目前为止的代码。
@commands.command(aliases=['dp'])
@commands.has_permissions(administrator=True)
async def dailyprompt(self, ctx, arbitrary_prefix, channel: discord.TextChannel, time_to_run: str, prompt=True): # This command seriously needs a database to run more efficiently. For now though, I just want it working.
if arbitrary_prefix.lower() == 'set' and channel is not None and time_to_run is not None:
time_zone = pytz.timezone('EST')
now = datetime.now(time_zone)
datetime_to_run = f'{str(now.date())} {time_to_run}'
datetime_to_run = datetime.strptime(datetime_to_run, '%Y-%m-%d %H:%M').astimezone(time_zone)
difference = (datetime_to_run - now).total_seconds()
if difference < 0:
datetime_to_run += timedelta(hours=24)
difference = (datetime_to_run - now).total_seconds()
if difference < 0:
await ctx.channel.send('Please input a valid time.')
raise ValueError
embed = discord.Embed(title='Daily Prompt Admin Notification', description=response, color=self.color)
await ctx.author.send(embed=embed)
await asyncio.sleep(difference)
await self.prompt(channel)
await asyncio.sleep(1)
await self.dailyprompt(self, ctx, arbitrary_prefix, channel, time_to_run)
【问题讨论】:
-
当您的程序从数据库加载信息时,您可以按 datetime_to_run 对信息进行排序,并为第一个任务创建一个异步任务(请参阅下面的链接),并等待该任务结束,然后再开始下一个任务一。 docs.python.org/3/library/asyncio-task.html#creating-tasks
标签: python python-3.x timer discord discord.py