如何在电报机器人 conversationHandler 的对话中保存数据

how to save data in conversation for telegram bot conversationHandler

我正在构建电报机器人。

我的机器人的一项功能要求机器人询问用户以在选项之间进行选择。 听到是我查询用户的代码

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
)

如您所见,在函数user_picked_store中我需要保存用户的选择(只有在用户选择了所有信息后我才能保存在数据库中)。 因此我需要访问用户所做的所有选择,我想将它存储在函数外部的对象中,因此所有函数都可以使用它,但是如果同时发出多个请求,这个解决方案将不起作用(每个请求都会覆盖另一个)。

有没有办法为对话的每个实例保存一个状态?

是否有每个会话的会话 ID?

你有 context.user_data 对话中持久的字典,你可以用它来存储所有用户选择。

例如

query = update.callback_query
querydata = query.data
context.user_data["key"] = querydata