0

I want to take the function every hour run , but if i insert my code into the bot file, he stop working:

now = datetime.datetime.now()      
today = now.day
hour = round(now.hour, 2)

while True:
    if today == now.day and (hour > 22.00 and hour < 23.00):
        bot.send_message(CHAT_ID, random.choice(welcomes))
        today += 1
    else:
        time.sleep(3600)

How i can fix it and to realize this function?

Aleksei Grabor
  • 153
  • 2
  • 8
  • I don't understand the purpose of the `if` condition. What difference does `today` make if this doesn't form part of the bot's response, and it's just going to sleep again for 3600 seconds? – roganjosh Mar 02 '19 at 09:24
  • Or, looking again, you don't actually want your function to run every hour, you want it to run _once per day_ at a set time interval, and you're checking for that interval every hour? – roganjosh Mar 02 '19 at 09:27
  • Possible duplicate of [Schedule a repeating event in Python 3](https://stackoverflow.com/questions/2398661/schedule-a-repeating-event-in-python-3) – jordiburgos Mar 02 '19 at 09:31
  • @roganjosh, I want the function to send a message once a day to a user at a certain point in time and at the same time not interfere with the work of other functions – Aleksei Grabor Mar 02 '19 at 09:34
  • 1. `now.hour` returns an `int` - no rounding is necessary. 2. Don't auto increment `today` - what will happen on the month's last day? 3. Use threading, or you'll be blocking the other functions you have. – TDG Mar 02 '19 at 10:29
  • @TDG , thanks , i didnt think about it – Aleksei Grabor Mar 02 '19 at 10:45

1 Answers1

0

The third line,

hour = round(now.hour, 2)

round will return 22.00 from 22:00 ~ 22:59, and 23.00 from 23:00 ~ 23:59.

So, your condition below never got it.

(hour > 22.00 and hour < 23.00)

(22.00 is not larger than 22.00 and 23.00 is not smaller than 23.00.)

Corrected condition is

(hour >= 22.00 and hour < 23.00)

or

(hour > 22.00 and hour <= 23.00)

or maybe you want

(hour == 22.00)