Scheduling recurring messages in Python Telegram bot

I’m new to building Telegram bots with Python. I want to send messages at specific times but I’m stuck. The callback_minute function seems to have issues with multiple arguments. I’ve looked at examples and docs for the run_repeating function but can’t figure it out.

My goal is to get the chat_id dynamically. Can anyone help?

Here’s a simplified version of what I’m trying:

import telegram
from telegram.ext import Updater, CommandHandler

def send_timed_message(context):
    context.bot.send_message(chat_id=context.job.context, text='Time-based message!')

def start(update, context):
    chat_id = update.effective_chat.id
    context.job_queue.run_repeating(send_timed_message, 60, context=chat_id)
    update.message.reply_text('Timed messages started!')

bot = telegram.Bot(token='YOUR_BOT_TOKEN')
updater = Updater(token='YOUR_BOT_TOKEN', use_context=True)

updater.dispatcher.add_handler(CommandHandler('start', start))

updater.start_polling()
updater.idle()

When I run this, I get an error about missing arguments. What am I doing wrong? How can I make this work?

hey there! i’ve had similar issues before. looks like ur on the right track tho. have u tried using context.job_queue.run_daily() instead? it might work better for specific times. also, double-check ur bot token - sometimes that can cause weird errors. good luck with ur project!

Your approach is sound, but there’s a small adjustment needed. In the send_timed_message function, modify the parameter to context: CallbackContext. This explicitly defines the expected object type, resolving the argument error.

Regarding dynamic chat_id retrieval, your implementation looks correct. The context=chat_id in run_repeating passes the chat_id to the job, which you then access via context.job.context in the message function.

For more precise timing, consider run_daily instead of run_repeating. It offers better control for specific times.

Lastly, ensure your bot has the necessary permissions in the target chat to avoid potential issues. Keep refining your code, and you’ll have a functional timed message system soon.

I’ve been working with Python Telegram bots for a while now, and I can relate to your struggle. Your code looks pretty close, but there’s a small tweak that should fix it. In your send_timed_message function, try changing the argument to context: CallbackContext instead of just context. This explicitly tells Python what type of object to expect, which can resolve those missing argument errors.

Also, consider using context.job_queue.run_daily() for more precise timing control. It allows you to set exact times for messages, which might be closer to what you need. One final tip: ensure your bot has the necessary permissions in the chat, as permission issues can sometimes present as other errors.

Keep at it – you’re definitely on the right path!