【问题标题】:Python Discord Bot Scheduled Task Blocks The Rest Of The CodePython Discord Bot 计划任务阻止了其余代码
【发布时间】:2021-09-15 14:56:54
【问题描述】:

我用 Python 构建了一个 Discord 机器人。该机器人有一些任务需要在一天中的不同时间运行,还有一些命令需要随时运行。

@bot.command(name = "how_are_you", help = "Asks: How Are You?")
async def ask_how_are_you(ctx):
    await ctx.send("How are you?")

@tasks.loop(hours = 24)
async def say_hello():
    channel = bot.get_channel(int(CHANNEL))
    await channel.send("Hello World")

@say_hello.before_loop
async def before():
    now = datetime.datetime.now()
    start_time = datetime.datetime(now.year, now.month, now.day, 20, 00)
    delta = start_time - now
    time.sleep(delta.total_seconds())
    await bot.wait_until_ready()
    print("Finished waiting")

然后我按如下方式运行机器人:

say_hello.start()
bot.run(TOKEN)

它是如何工作的:我希望say_hello() 每天在 20:00 运行。 before() 函数获取当前时间并检查在 20.00 之前错过了多少秒,然后等待该秒数。 问题是,在能够向机器人发送命令之前,我需要等待 before() 函数完成等待。这可能需要一段时间,因为如果现在是 17.00,我需要等到 20.00 before() 完成等待。 更糟糕的是,如果我有一个每周运行的任务,比如说,每个星期五 @ 20.00 而今天是星期二,我需要等待 3 天才能发送命令。

如何让任务在后台等待并同时向机器人发送命令?提前致谢。

【问题讨论】:

    标签: python discord discord.py python-asyncio


    【解决方案1】:

    我实际上设法解决了这个问题。 before()函数需要修改如下:

    @say_hello.before_loop
    async def before():
        now = datetime.datetime.now()
        start_time = datetime.datetime(now.year, now.month, now.day, 20, 00)
        delta = start_time - now
        await asyncio.sleep(delta.total_seconds()) #THIS CHANGED
        await bot.wait_until_ready()
        print("Finished waiting")
    

    重要的是记住import asyncio,就像你不这样做一样,代码不会给你任何错误但它不会工作。

    p>

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2023-01-23
      • 2018-05-31
      • 2021-01-02
      • 2020-08-02
      • 2017-04-06
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多