0

I'm trying to create a discord bot which takes a date and time from the command and sends a message 1 minute before said date/time.

Below is a portion of the code I have written. The command works as expected right now but the task loop is not sending a message.

async def on_ready():
    print("Our Bot is online!")
    task_loop.start()

@bot.command()
async def cfg(ctx, ac: str, date: str):
    print(datetime.now())
    date = datetime.strptime(date, "%Y-%m-%d_%H:%M")
    embed = discord.Embed(title="NOTIFICATION")
    embed.add_field(name=ac + " test", value=date)
    await ctx.send(embed=embed)

@tasks.loop(seconds=1)
async def task_loop():
    if datetime.now() == date - timedelta(minutes=1):
        print("test")
        embed = discord.Embed(title="NOTIFICATION")
        embed.add_field(name=ac + " blah blah blah", value="blah")
        await ctx.send(content=f"{ctx.message.guild.default_role}", embed=embed)
    else:
        print("nope")

1 Answers1

1

So, if you got time in seconds, you can use asyncio.sleep(seconds) to run code after a certian time (-60 if you need to send a message 1 minute before said date/time)

@bot.command()
async def cfg(ctx, ac: str, date: str):
    date = datetime.strptime(date, "%Y-%m-%d_%H:%M")
    # x.timestamp() - get time in seconds
    to_wait = date.timestamp() - datetime.datetime.now().timestamp() # Time to wait
    to_wait = to_wait - 60 # If you need to send a message 1 minute before said date/time
    await asyncio.sleep(to_wait)
    print("Now!")
Kalosst0
  • 38
  • 4
  • Thanks, this worked! Quick follow-up question: Do you know how to make the bot work in UTC rather than my native timezone (EST)? I want it to read the time in from the command in UTC. – Ben Whittington Mar 15 '23 at 11:17
  • Not sure what do you want (don't forget to mark this answer as an answer), but I think this can help you > https://stackoverflow.com/questions/79797/how-to-convert-local-time-string-to-utc – Kalosst0 Mar 15 '23 at 11:38