(python) Telegram bot- how to send messages periodically?

You need to use the context parameter when defining the job in your function. Look at this example:

   from telegram.ext import Updater, CommandHandler, MessageHandler,    Filters, InlineQueryHandler


def sayhi(bot, job):
    job.context.message.reply_text("hi")

def time(bot, update,job_queue):
    job = job_queue.run_repeating(sayhi, 5, context=update)

def main():
    updater = Updater("BOT TOKEN")
    dp = updater.dispatcher
    dp.add_handler(MessageHandler(Filters.text , time,pass_job_queue=True))


    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Now in your call back function wherever you need update. type job.context instead.


To send messages periodically, you can use JobQueue Extention from python-telegram-bot

Here is an example

from telegram.ext import Updater, CommandHandler

def callback_alarm(bot, job):
    bot.send_message(chat_id=job.context, text='Alarm')

def callback_timer(bot, update, job_queue):
    bot.send_message(chat_id=update.message.chat_id,
                      text='Starting!')
    job_queue.run_repeating(callback_alarm, 5, context=update.message.chat_id)

def stop_timer(bot, update, job_queue):
    bot.send_message(chat_id=update.message.chat_id,
                      text='Stoped!')
    job_queue.stop()

updater = Updater("YOUR_TOKEN")
updater.dispatcher.add_handler(CommandHandler('start', callback_timer, pass_job_queue=True))
updater.dispatcher.add_handler(CommandHandler('stop', stop_timer, pass_job_queue=True))

updater.start_polling()

the /start command will start the JobQueue and will send a message with an interval of 5 seconds, and the queue can be stopped by /stop command.