How to schedule recurring messages with python-telegram-bot

I’m new to making Telegram bots with Python. I want to send messages at set times but I’m having trouble. The callback_minute function doesn’t seem to work right with multiple arguments. I’ve looked at examples and docs for the run_repeating function but I’m stuck.

Here’s what I’m trying to do:

def callback_minute(self, context):
    context.bot.send_message(chat_id='-1001198785547', text='Time check!')

j = updater.job_queue
j.run_repeating(bot.callback_minute, interval=60, first=10)

But I get this error:

ValueError: The following arguments have not been supplied: context

How can I fix this to send scheduled messages? I want to get the chat_id dynamically if possible. Any tips?

hey there! i’ve dealt with this before. try changing ur callback function like this:

def callback_minute(context):
context.bot.send_message(chat_id=context.job.context, text=‘Time check!’)

j.run_repeating(callback_minute, interval=60, first=10, context=‘-1001198785547’)

this should fix the error and let u send scheduled msgs. good luck!

I’ve been through this exact issue when setting up scheduled messages for my Telegram bot. The problem is likely with how you’re passing the callback function to run_repeating.

Try modifying your code like this:

def callback_minute(context):
    context.bot.send_message(chat_id='-1001198785547', text='Time check!')

j = updater.job_queue
j.run_repeating(callback_minute, interval=60, first=10)

Notice I removed ‘self’ from the function definition and call. This should resolve the ValueError you’re seeing.

For getting the chat_id dynamically, you could store it in context.bot_data when the bot first interacts with a chat, then retrieve it in the callback. Something like:

def callback_minute(context):
    chat_id = context.bot_data.get('chat_id', 'default_chat_id')
    context.bot.send_message(chat_id=chat_id, text='Time check!')

Hope this helps! Let me know if you run into any other issues.

I encountered a similar issue when implementing scheduled messages in my Telegram bot. The key is to understand how the job queue works with context.

Here’s a solution that should work:

def callback_minute(context):
    chat_id = context.job.context
    context.bot.send_message(chat_id=chat_id, text='Time check!')

j = updater.job_queue
j.run_repeating(callback_minute, interval=60, first=10, context='-1001198785547')

This approach passes the chat_id as context to the job, making it accessible within the callback function. It’s more flexible as you can easily change the chat_id for different jobs.

For dynamic chat_ids, consider storing them in a database or configuration file, then retrieve them when setting up the job queue. This allows for easier management of multiple chats and schedules.