skip to Main Content

I am trying to create a Telegram bot that sends a message at a specific time, 5:30pm. However, the ways a was trying are not correct.

I wanted to trigger send_message regarding to the time and without the necessity of the user to send any /command.

import telebot
import datetime

TOKEN = 'MyToken'
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def send_welcome(message):
    message_id=message.chat.id
    bot.reply_to(message,"Welcome")


bot.polling()

Until now I was trying to add something like that, of course it is not python but kind of pseudocode just to explain:

if currenttime=17:30
 send_message(idchat, "mymessage")

Thank you in advance.

2

Answers


  1. If I understand correctly, you need to check your system time before sending a message, you could use the following code [source]:

    from datetime import datetime
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print("Current Time =", current_time)
    

    To send a message you could use the following code [source]:

    def test_send_message():
            text = 'CI Test Message'
            tb = telebot.TeleBot(TOKEN)
            ret_msg = tb.send_message(CHAT_ID, text)
            assert ret_msg.message_id 
    

    To compare the time, you may use:

    if current_time=='17:30:00':
        test_send_message()
    
    Login or Signup to reply.
  2. You can use schedule python library.
    First of all import the necessary modules

    import schedule
    import time
    import telegram
    

    Then you have to create a function that will repeat in every x time.
    Here the bot will send me message in every 5 seconds.

    TOKEN='your_token'
    bot = telegram.Bot(token=TOKEN)
    def job():
        bot.sendMessage(chat_id=<chat_id>, text="Hello")
    
    schedule.every(5).seconds.do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    For more informations about schedule Read the documentation

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search