Search code examples
pythontelegramtelebot

How using telebot make a bot send message ONCE in a specific time?


I'm writing a bot using telebot and bot needs to remind the user adbout his departure. I got a departure date, and I need ro sent a message a day before departure. I need to send it just once.

I tried shedule python module and understood, that it can't send message once, and it can't send message in the next month for example, or I don't understand how to make it do this. Can you explain me, please, is there another way to do this or how to make sheduler make that i need?


Solution

  • Please, check the code below. It runs a thread that executes every second and you can program an action at specific time or each n seconds.

    Please, note that you have to specify chat_id

    #this timer can be used to execute tasks from time to time or at a specific time
    
    import telebot
    import time, datetime
    import threading 
    
    bot = telebot.TeleBot('TOKEN')
    
    
    chat_id = None
    
    def tic_tac():
    
        i = 0
    
        while True:
    
            this_moment = datetime.datetime.now()
    
            #Executes each 60 secondss
            if ((i % 60) == 0):
                if chat_id:
                    bot.send_message(chat_id, "Hello! How are you?")
    
            #Check if it is 12:00:00; if it is true sends the message
            if this_moment.hour == 12 and this_moment.minute == 0 and this_moment.second == 0:
                if chat_id:
                    bot.send_message(chat_id, "It is the noon!")
    
            i += 1
            time.sleep(1)
    
    #Needs to be started to know the chat id to send messages
    @bot.message_handler(commands=['start'])
    def save_chat_id(message):
        global chat_id
        chat_id = message.chat.id 
        bot.send_message(chat_id, 'I got it', reply_to_message_id=message.message_id)
    
    
    
    timThr = threading.Thread(target=tic_tac)
    timThr.start()
    bot.polling(none_stop=True)```