python - 如何使任务与 UTC 时间同步并每 6 小时运行一次 discord.py
问题描述
我想将我的任务与我的任务同步,该任务每 6 小时清除一个频道的所有消息。我有这个代码,它每小时运行一次,与 UTC 时间同步(例如,它在下午 1:00 运行,然后在下午 2:00 运行,无论我何时启动脚本),但现在我想这样做该脚本每 6 小时在(上午 12:00、上午 6:00、下午 12:00、下午 6:00)UTC 运行一次,我试过了,但我似乎无法弄清楚。请帮我解决这个问题。谢谢。
代码:
import discord
import os
import asyncio
from discord.ext import commands,tasks
from datetime import datetime
class Events(commands.Cog):
def __init__(self, client):
self.client = client
@tasks.loop(hours=1)
async def bot_test_clear(self):
channel_bot_test = self.client.get_channel(os.getenv('bot-test-text'))
messages = await channel_bot_test.history(limit=100).flatten()
if not messages:
return
embed = discord.Embed(description='It has been 1 hour, clearing chats...', color=0xff0000)
await channel_bot_test.send(embed=embed)
await asyncio.sleep(10)
await channel_bot_test.purge(limit=None)
@bot_test_clear.before_loop()
async def prep(self):
now = datetime.utcnow()
future = datetime(now.year, now.month, now.day, now.hour +1,0)
delta = (future - now).total_second()
print(round(delta/60))
await asyncio(delta)
@commands.Cog.listener()
async def on_ready(self):
self.bot_text_clear.start()
print(f'{self.client.user} is now online')
def setup(client):
client.add_cog(Events(client))
解决方案
由于我已经回答了您之前的代码所基于的问题,因此我也将尝试回答这个问题。
from datetime import datetime, timedelta
@tasks.loop(hours=6)
async def bot_test_clear(self):
...
@bot_test_clear.before_loop
async def prep(self):
hour, minute = 12, 00 # 12:00 am, change accordingly
now = datetime.utcnow()
future = datetime(now.year, now.month, now.day, hour, minute)
if future < now: # if time is in the past
future += timedelta(days=1) # delay to the next day
delta = (future - now).total_second()
await asyncio.sleep(delta)
bot_test_clear.start() # you don't need to start it in the on_ready event
代码非常相似,唯一改变的是传递给 datetime 构造函数的小时和分钟。
推荐阅读
- python - 如何为列表中的每个元素分配条件
- python - 使用 numpy.ndarray.ndim(arr) 直接获取维数
- android - JSON对象到字符串数组
- azure - Deploy console app from Azure Devops (cloud version) to a machine with a Microsoft-provided host agent (Failed to create PSDrive with destination...)
- javascript - 无法将复选框值发送到 php
- reporting-services - 一过滤多列SSRS
- c - 没有鼠标的win32,如何将键盘快捷键分配给按钮
- java - 如何在 Webflux 功能端点的测试中禁用 Spring Security
- azure-ad-graph-api - 如何设置获取使用 Graph API 的 Token
- sql - 如何将包含自身的值放入 SQL 中的查询