3

In the following code how can we pass the context.args and context to another function, in this case callback_search_msgs

def search_msgs(update, context):
    print('In TG, args', context.args)
    context.job_queue.run_once(callback_search_msgs, 1, context=context, job_kwargs={'keys': context.args})

def callback_search_msgs(context, keys):
    print('Args', keys)
    chat_id = context.job.context
    print('Chat ID ', chat_id)

def main():
    updater = Updater(token, use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("search_msgs",search_msgs, pass_job_queue=True,
                                  pass_user_data=True))

    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()
CallMeStag
  • 5,467
  • 1
  • 7
  • 22
Vivek Singh
  • 346
  • 3
  • 14

1 Answers1

5

A few notes:

  • job callbacks accept exactly one argument of type CallbackContext. Not two.
  • the job_kwargs parameter is used to pass keywoard argument to the APScheduler backend, on which JobQueue is built. The way you're trying to use it doesn't work.
  • if you want to know only the chat_id in the job, you don't have to pass the whole context argument of search_msgs. Just do context.job_queue.run_once(..., context=chat_id,...)
  • if you want to pass both the chat_id and context.args you can e.g. pass them as tuple:
    job_queue.run_once(..., context=(chat_id, context.args), ...)
    
    and then retrieve them in the job via chat_id, args = context.job.context.
  • Since you're using use_context=True (which is the default in v13+, btw), the pass_* parameters of CommandHandler (or any other handler) have no effect at all.

I suggest to carefully read


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

CallMeStag
  • 5,467
  • 1
  • 7
  • 22