Creating a Python Telegram bot that sends periodic messages

Hey everyone! I’m new to bot development and I’ve got a basic Telegram bot up and running. But I’m stuck on how to make it send messages at regular intervals when a user types /begin_schedule. I tried using a while loop, but it’s not ideal since it blocks other interactions.

I want users to be able to start and stop this scheduled messaging with commands like /begin_schedule and /end_schedule. I’ve seen other posts about this, but I can’t get them to work with my setup.

Here’s a simplified version of my code:

from telegram.ext import Updater, CommandHandler

def greet(update, context):
    update.message.reply_text('Hello there!')

def begin_schedule(update, context):
    # This is where I need help
    # How to send a message every X hours?
    pass

def main():
    bot_token = 'YOUR_BOT_TOKEN'
    updater = Updater(bot_token, use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler('greet', greet))
    dp.add_handler(CommandHandler('begin_schedule', begin_schedule))

    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Any ideas on how to implement the scheduled messaging without blocking other bot functions? Thanks in advance!

For your scheduled messaging feature, I recommend using the ‘schedule’ library in Python so you can keep your main thread free. You can install it with pip install schedule. After installing, import the library and define a function for your scheduled task. Then use schedule.every().hour.do(your_function) to schedule the task and run schedule.run_pending() in a separate thread. This way the bot remains responsive. Also, make sure you have a mechanism to cancel the schedule when the /end_schedule command is issued. I hope this helps with your bot development.

Hey there! I’ve been working with Telegram bots for quite a while and found that APScheduler is a reliable choice for scheduling periodic tasks without blocking other bot functions. You can install APScheduler using pip and import it into your script. In your main function, set up the scheduler and design a function to send your periodic messages. This method gives you the flexibility to start and stop scheduled tasks as needed by storing the job so you can cancel it later. This approach has worked well for me and should integrate smoothly with your bot.

hi miar, try using telegram’s job_queue for sched messaging w/thout blocking. in /begin_schedule, run run_repeating and later cancel it on /end_schedule. hope that helps!