【问题标题】:How To Loop Tasks In Discord.Py With Different Loops For Each Guild如何在 Discord.Py 中为每个公会使用不同的循环来循环任务
【发布时间】: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


【解决方案1】:

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

from json import load, dumps
global Path
Path = r"C:\\Path\to\File.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()

你需要这样的东西吗?

【讨论】:

  • 我已经有一个数据库,并且正在做类似的事情。我只是想看看是否有更好的方法,也许我错过的 Discord.py 中内置的一些东西可以简化任务。不过还是谢谢你。会投票,因为这是一个很好的答案。
猜你喜欢
  • 2020-09-07
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 2021-12-07
  • 2023-03-23
相关资源
最近更新 更多