owcs
owcs

Reputation: 129

Trigger an event every week at a specific day and time in discord.py

I want to trigger something every Wednesday at 3:30 UTC on a Discord bot using discord.py. I tried modifying the code in this answer, but couldn't figure out how to get it to run every week instead of every day. I am not very familiar with tasks, so I couldn't get it to work from scratch either.

Upvotes: 2

Views: 2832

Answers (1)

Abdulaziz
Abdulaziz

Reputation: 3426

This is not an ideal method but it will work.

Taking my answer from that question, You can make it loop every 7 days but that would start at the start of the bot. Use a before_loop to set the starting time for the 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)

Docs:

Upvotes: 1

Related Questions