D.sLyak
D.sLyak

Reputation: 13

How do make an event activate on a specific Unix timestamp. in discord.py?

I am making a bot that has an announcement at a different time on each weekday. I want to go about the process of making this by having 5 discord task loops that send the announcement on their respective days. They will activate on their respective Unix timestamps and then will reactivate on the the timestamp is refreshed for the next week. How do I make a an @client.event that activates on a Unix timestamp?

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("")

Upvotes: 0

Views: 823

Answers (1)

bravosierra99
bravosierra99

Reputation: 1371

I would consider a more naive solution. Simply loop frequently and check if you at lunch time, if so send the lunch message. I tend to use arrow because I find it easy to use... you could implement with other libraries

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)

Upvotes: 1

Related Questions