【问题标题】:Trigger an event every week at a specific day and time in discord.py在 discord.py 中的特定日期和时间每周触发一个事件
【发布时间】:2021-09-15 08:06:42
【问题描述】:

我想在每周三 3:30 UTC 使用 discord.py 在 Discord 机器人上触发一些事情。我尝试修改this answer 中的代码,但无法弄清楚如何让它每周而不是每天运行。我对任务不是很熟悉,所以我也无法从头开始工作。

【问题讨论】:

  • 你考虑过使用 webhook 吗?然后通过 cronjob 或在线服务激活它

标签: discord discord.py


【解决方案1】:

这不是一个理想的方法,但它会起作用。

从那个问题中得到我的答案,你可以让它每 7 天循环一次,但这将从机器人开始时开始。使用before_loop 设置循环的开始时间。

import asyncio
import datetime as dt


@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print("------")
    msg1.start()


# 7 days => 24 hour * 7 days = 168
@tasks.loop(hours=168)
async def msg1():
    message_channel = bot.get_channel(123)
    await message_channel.send("test 1")


@msg1.before_loop
async def before_msg1():
    # loop the whole 7 day (60 sec 60 min 24 hours 7 days)
    for _ in range(60*60*24*7):  
        if dt.datetime.utcnow().strftime("%H:%M UTC %a") == "03:30 UTC Wed":
            print('It is time')
            return

        # wait some time before another loop. Don't make it more than 60 sec or it will skip
        await asyncio.sleep(30)

文档:

【讨论】:

  • 会在运行后的第一个星期三开始,还是必须等到下周才能触发?我问这个是因为我正在尝试对其进行测试,但它没有运行。例如,我将 03:30 UTC Wed 替换为 20:55 UTC Mon,但在 20:55 时没有任何反应。
  • 我使用了datetime.now,它显示了当地时间,将代码更改为使用utcnow。你可以随时print(dt.datetime.now().strftime("%H:%M UTC %a"))查看你得到了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多