2

So I want my discord bot to send out a message in the server every morning at 7 am. Using my variable time which is:

time = datetime.datetime.now()

and doing time.hour and time.minute, I can make it print something at the time i want using:

if time.hour == 7:
    print('Its 7 am')

but using a whle statement datetime doesnt actually refresh the time. Second of all if there are any discord.py people how would i send the message without using an event refernec or command?

Remi_Zacharias
  • 288
  • 2
  • 4
  • 16

3 Answers3

1

This should do what you want.

time = datetime.datetime.now

while True:
  if time().hour == 7 and time().minute == 0:
    print("Its 7 am")
  sleep(60)

The reason the time doesn't actually refresh in your code is that you are storing the result of a function in the variable, not the function itself. If you don't include the parenthesis then the function gets stored in the variable so it can be called later using variable().

Gingeh
  • 26
  • 2
  • oh that makes sense, but what does the sleep(60) do? Is that like a refresh timer so every 60 seconds it refreshes? – Remi_Zacharias Sep 11 '20 at 09:23
  • Without the sleep(60) it would print every time it repeats until 7:01, the sleep(60) makes sure it only checks every minute. – Gingeh Sep 12 '20 at 00:08
0

This question could already be answered on the following link:

Python - Start a Function at Given Time

Given the following information:

Reading the docs from http://docs.python.org/py3k/library/sched.html:

Going from that we need to work out a delay (in seconds)...

from datetime import datetime
now = datetime.now()

Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)

# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()

You can then use delay to pass into a threading.Timer instance, eg:

threading.Timer(delay, self.update).start()
0

You could take a look at https://schedule.readthedocs.io/en/stable/

Install schedule with pip:

$ pip install schedule

You could do something like that:

import schedule
import time

def job():
    print("Its 7 am")

schedule.every().day.at("07:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
JJose
  • 77
  • 7