如何在Discord.Py中循环每个公会的不同循环任务



我想在Discord.py中循环一个任务,它将在不同的时间循环几个不同的公会。例如,如果一个公会在20:00调用该命令,另一个公会在13:00调用该命令,我希望能够在每个公会每天的同一时间(在他们指定的时间)运行该命令。我还希望在维护后重新启动服务器时重新加载这些命令。

因此,基本上,我希望在每个服务器上每天的不同时间运行某个命令。我还希望计时器保存,以便它们在服务器重启后存在。

我现在这样做的方式是通过一个外部数据库来存储运行命令所需的所有必要信息,在启动时加载该信息,并在启动时调用async命令,基本上重新加载所有保存的计时器。

这是我到目前为止的代码。

@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)

您应该将数据存储到.json文件中,如下所示:

from json import load, dumps
global Path
Path = r"C:\PathtoFile.json"
global Dictionary
Dictionary = {}
...
@Bot.command()
async def SetHour(ctx, hour:int):
#Put there functions to make hour to be a datetime.data or datetime.time object
global Dictionary
Dictionary[ctx.guild.id] = hour
DictionaryEncoded = dumps(Dictionary)
Database = open(Path, 'w')
Database.write(DictionaryEncoded)
Database.close()
你需要这样的史密斯吗?

最新更新