如何使事件在特定的Unix时间戳上激活。不和谐?

2024-05-16 02:43:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个机器人,在每个工作日的不同时间发布公告。我想通过5个discord任务循环在各自的日期发送公告来完成这一过程。它们将在各自的Unix时间戳上激活,然后在刷新下周的时间戳时重新激活。 如何生成在Unix时间戳上激活的@client.event

import discord
from discord.ext import commands, tasks
import random
import datetime

client = commands.Bot(command_prefix='.')

orig = datetime.datetime.fromtimestamp(1425917335)
new = orig + datetime.timedelta(days=90)
target_channel_id = 123456789
list_warning = ["T minus... 5 minutes... until detonation.", "Teacher is waiting. Get your ass back in 5 minutes.", "300 seconds unt-, 299 seconds unt-, 298 seconds unt-...",
                "Chow down boys, lunch ends in 5 minutes.", "Looks like you've got some schoolin' to do."]
list_time = [1, 10]


#loops the 5 minute warning for lunch to end
@tasks.loop(seconds=)
async def called_once_a_day():
    message_channel = client.get_channel(target_channel_id)
    print(f"Got channel {message_channel}")
    await message_channel.send(random.choice(list_warning))
    org = orig + datetime.timedelta(days=7)

@called_once_a_day.before_loop
async def before():
    await client.wait_until_ready()
    print("Finished waiting")


called_once_a_day.start()


client.run("")

Tags: importclientdatetime时间channeluntlistseconds
1条回答
网友
1楼 · 发布于 2024-05-16 02:43:17
我会考虑一个更幼稚的解决方案。只需频繁循环并检查您是否在午餐时间,如果是,请发送午餐信息。我倾向于使用箭头,因为我发现它很容易使用。。。您可以与其他库一起实现

tuesday_lunch_time = arrow.get("1230","HHmm")


#loop every minute so we are within a minute of lunch time.. you could change this to loop more often
@tasks.loop(minutes=1)
async def called_once_a_day():
    now = arrow.now()
    if now.weekday()== 1: #is today tuesday, don't ask me why tuesday is 1
        if tuesday_lunch_time.shift(minutes=2).time() > now.time > tuesday_lunch_time.time():  ###this checks if you are within two minutes after lunch time, you could change this if you want to say have it be early, because of our loop it should be within a minute but I picked two minutes to be safe
            message_channel = client.get_channel(target_channel_id)
            print(f"Got channel {message_channel}")
            await message_channel.send(random.choice(list_warning))
            #to get out of the conditional above, so you don't send multiple times
            await asyncio.sleep(720)

相关问题 更多 >