skip to Main Content

I need to take chat_id in repeating task to send users some repeating but personalized messages. How can I take chat_id in repeating func?

def repeating(context):

    context.bot.send_message(chat_id=<CHAT_ID>,text=res["message"])

def main():
    updater = Updater(constants.BOT_API_KEY, use_context= True)


    job_queue = JobQueue()
    dp = updater.dispatcher
    job_queue.set_dispatcher(dp)
    job_queue.run_repeating(callback=repeating,interval=5)


    updater.start_polling()
    job_queue.start()

    updater.idle()

main()

2

Answers


  1. For me, the easiest way is to store those values in dict.
    In code it should look like this:

    updater = Updater(constants.BOT_API_KEY, use_context= True)
    dp = updater.dispatcher
    
    mailinglist={123:'personal message'} 
    #you can use a list (mailinglist=[123,1234,...]), but there will be no personal messages
    
    def mailing():
        for user_id in mailinglist: #mailinglist[user_id] gets personal message 
            bot.send_message(user_id, mailinglist[user_id])
    
    
    if __name__ == '__main__':
    
        job_queue = JobQueue()
        job_queue.set_dispatcher(dp)
        job_queue.run_repeating(callback=mailing,interval=5)
    
        updater.idle()
     
       
    
    Login or Signup to reply.
  2. The methods JobQueue.run_* have a parameter called context that can be used to pass information to the callback. In the callback, the contents of this parameter are available as context.job.context. Please have a look at

    where the latter two showcase how to use the context parameter.

    Also note that you should not manually instantiate a JobQueue – use updater.job_queue instead. Otherwise you’ll also have to take care of actually starting and shutting down the JobQueue.


    Disclaimer: I’m currently the maintainer of python-telegram-bot.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search