Search code examples
python-3.xtelegramtelegram-botpython-telegram-bot

Send telegram message periodically using bot


Give the code below:

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")

Is it possible to call this function periodically and make my bot send the message to the user automatically instead of the user typing "/start"


Solution

  • you need to create a job object which is delivered by python-telegram-bot so to simply run the function start let's say every minute you could use this approach:

    j= updater.job_queue
    
    def start(update, context):
        context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
    
    j.run_repeating(start,interval = 60  ,first= 0 )
    updater.start_polling()
    

    and if you wanted to run it every day at specific time you could use:

    import datetime 
    j= updater.job_queue
    
    def start(update, context):
        context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
    
    t= datetime.time(6, 15, 00, 000000)
    
    j.run_daily(start, t, days=(0, 1, 2, 3, 4, 5, 6), context=None, name=None)
    updater.start_polling()
    
    

    note that there's no handlers to be added to the dispatcher.

    and you probably should know that the datetime.time object uses the UTC time if not modified.

    for more information check Extensions – JobQueue here