skip to Main Content

I am building a telegram bot.

one of the functionalities of my bot require the bot to query the user to pick between choices.
Hear is my code that query the user

def entry_point(update: Update, context: CallbackContext):
    companies_btn = [
        [
            InlineKeyboardButton(company.company_name, callback_data=company.id)
            for company in get_companies()
        ]
    ]
    companies_keyword = InlineKeyboardMarkup(companies_btn)
    update.message.reply_text(
        "Please pick a company", reply_markup=companies_keyword
    )
    return 1


def user_picked_company(update: Update, context: CallbackContext):
    stores_btn = [
        [
            InlineKeyboardButton(store.store_name, callback_data=store.id)
            for store in get_stores()
        ]
    ]

    store_keyword = InlineKeyboardMarkup(stores_btn)
    update.message.reply_text(
        "Please pick a store", reply_markup=store_keyword
    )
    return 2


def user_picked_store(update: Update, context: CallbackContext):
    save_user_choices()


handler = ConversationHandler(
    entry_points=[CommandHandler('pick', entry_point)],
    states={
        1: CallbackQueryHandler(user_picked_company),
        2: CallbackQueryHandler(user_picked_store)
    },
    fallbacks=[entry_point],
    per_chat=True,
    per_user=True,
    per_message=True
)

as you can see, in the function user_picked_store I need to save the user choices (I can save in the db only after the user picked all the information).
Therefore I need access to the all the choices the user made, I thought to store it in an object outside the function and so all the function can use it, however this solution will not work if multiple request will be made at the same time (each request will override the other).

Is there a way to save a state for each instance of the conversation?

Is there any session id for each conversation?

2

Answers


  1. You have context.user_data dict that is persistent acrross conversation, you can use it to store there all user choices.

    e.g.

    query = update.callback_query
    querydata = query.data
    context.user_data["key"] = querydata
    
    Login or Signup to reply.
  2. Yes the context.user_data holds till the conversation lasts with the user.

    To use the context.user_data dict, we need to mention as context.user_data.get(‘var_name’)

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