Scheduling hourly messages with Python Telegram Bot

Hey everyone, I’m stuck trying to set up a bot that sends messages every hour. I’ve searched everywhere and tried different solutions but can’t get the job queue to work. Here’s the code I’m using, which I adapted from the official python-telegram-bot examples:

from telegram.ext import Updater

updater = Updater('my_bot_token', use_context=True)
job_queue = updater.job_queue

def send_hourly_message(context):
    context.bot.send_message(chat_id='my_chat_id', text='Hourly update!')

hourly_job = job_queue.run_repeating(send_hourly_message, interval=3600)
updater.start_polling()
updater.idle()

When I run this, I get an error about scheduling new futures after interpreter shutdown. Any ideas on what I’m doing wrong or how to fix this? I’m pretty new to working with job queues in Python, so any help would be awesome. Thanks!

I’ve been down this road before, and it can be frustrating. One thing that helped me was wrapping the main bot logic in a function and using a try-except block. Something like this:

def main():
    updater = Updater('your_token', use_context=True)
    job_queue = updater.job_queue
    
    def send_hourly_message(context):
        context.bot.send_message(chat_id='your_chat_id', text='Hourly update!')
    
    job_queue.run_repeating(send_hourly_message, interval=3600)
    
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Bot stopped gracefully')
    except Exception as e:
        print(f'Error occurred: {e}')

This structure helped me catch errors and gracefully shut down the bot. Also, make sure your Python environment has the correct dependencies installed. If you’re still having issues, you might want to check your bot token and chat ID to ensure they’re correct.

I’ve encountered similar issues with scheduling in python-telegram-bot. The error you’re seeing typically occurs when the script is exiting before the job queue has a chance to run. Here’s what worked for me:

Try moving the updater.idle() call immediately after updater.start_polling(). This keeps the main thread alive and allows the job queue to run.

Also, ensure you’re using the latest version of python-telegram-bot, as older versions had some quirks with job queues.

If that doesn’t solve it, you might want to consider using a more robust scheduling library like APScheduler in conjunction with your bot. It offers more flexibility and reliability for recurring tasks.

Let me know if you need any clarification on these suggestions. Good luck with your bot!

hey, i had similar probs. try adding a sleep() call after start_polling(). like this:

import time

updater.start_polling()
time.sleep(1)
updater.idle()

this gives the job queue time to initialize. worked for me! lmk if it helps