V
V
Valery2020-09-13 00:31:28
Python
Valery, 2020-09-13 00:31:28

How to send a message to an individual user after a certain amount of time?

There is a bot in which the user switches to the bot, starts it with the /start command.
After the bot sends a specific message.
After a certain period of time, the bot sends 2 more messages, message #1 at 12:00, message #2 at 18:00.
The interval that should be before sending messages #1 and #2 for each user is 24 hours.
How can all this be implemented and is it possible at all?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2020-09-13
@ApXNTekToP

The easiest way would be to implement all this through threading and time.sleep()
Here, 2 threads are created that send messages, and then go to sleep for 24 hours

import datetime as dt
from threading import Thread
from time import sleep


class SendThread(Thread):
    def __init__(self, hours: int):
        Thread.__init__(self)
        self.hours = hours

    def run(self):
        # Здесь код, который будет выполняться в потоке
        day_to_seconds = 24 * 60 * 60
        now = dt.datetime.now()
        today_time = now - dt.datetime(year=now.year, month=now.month, day=now.day)
        seconds = today_time / dt.timedelta(seconds=1)
        time_to_next_call = self.hours * 60 * 60 - seconds  # Время в секундах до первого вызова
        if time_to_next_call < 0:
            time_to_next_call += day_to_seconds
        sleep(time_to_next_call)

        while True:
            #  Ваш код (отправка сообщения)
            # ...

            sleep(day_to_seconds)


# Ваш код...

if command == "/start":
    send_12 = SendThread(hours=12)  # сообщение #1
    send_18 = SendThread(hours=18)  # сообщение #2

    send_12.start()
    send_18.start()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question