How to send automated messages with telegram bot library in Python

I want to create a telegram bot that can send messages automatically without needing users to type anything first. I’m using the python telegram bot library but my code isn’t working. The bot runs without any error messages but no messages are being sent to my group chat.

def notify_users(bot_context):
    bot_context.bot.send_message(chat_id=-789123456, text='Hello everyone!')
    # I got this group ID from the telegram API getUpdates method

def start_bot():
    bot_updater = Updater(BOT_TOKEN)
    message_dispatcher = bot_updater.dispatcher
    
    notification_handler = MessageHandler(Filters.text & (~Filters.command), notify_users)
    message_dispatcher.add_handler(notification_handler)
    
    bot_updater.start_polling()
    bot_updater.idle()

start_bot()

What am I doing wrong here? Is there a better way to send messages proactively with this library?

I encountered a similar issue when creating my own Telegram bot. The structure of your code appears sound, but the problem lies in combining reactive and proactive messaging methods. A MessageHandler only activates upon user interaction, so you need to implement a different approach for automatic messages. One effective solution is to create a dedicated thread or utilize the job queue system to schedule the send_message function at regular intervals without depending on user input. Also, ensure your bot possesses the necessary permissions to send messages in the group. I faced multiple delays due to overlooked permission settings, so it’s crucial to double-check that your bot is correctly configured with admin access in the group.

The issue is that your notify_users function is set up as a message handler, which means it only executes when someone sends a message to the bot. If you want truly automated messages without any user interaction, you need to separate the sending logic from the handler system entirely. Try creating a simple loop with time.sleep() or use threading.Timer to call your send_message function at regular intervals. Also double check that your bot has permission to post in that group chat and the chat_id is correct - sometimes bots fail silently when they lack proper permissions.

your using MessageHandler which only triggers when users send messages. for automated sending try job_queue instead - it lets you schedule messages without user input. something like job_queue.run_repeating(notify_users, interval=300) should work better for proactive messaging.