【发布时间】:2021-09-15 08:06:42
【问题描述】:
我想在每周三 3:30 UTC 使用 discord.py 在 Discord 机器人上触发一些事情。我尝试修改this answer 中的代码,但无法弄清楚如何让它每周而不是每天运行。我对任务不是很熟悉,所以我也无法从头开始工作。
【问题讨论】:
-
你考虑过使用 webhook 吗?然后通过 cronjob 或在线服务激活它
标签: discord discord.py
我想在每周三 3:30 UTC 使用 discord.py 在 Discord 机器人上触发一些事情。我尝试修改this answer 中的代码,但无法弄清楚如何让它每周而不是每天运行。我对任务不是很熟悉,所以我也无法从头开始工作。
【问题讨论】:
标签: discord discord.py
这不是一个理想的方法,但它会起作用。
从那个问题中得到我的答案,你可以让它每 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"))查看你得到了什么。