【问题标题】:how to save data in conversation for telegram bot conversationHandler如何在电报机器人对话处理程序的对话中保存数据
【发布时间】:2020-03-27 12:32:15
【问题描述】:

我正在构建一个电报机器人。

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

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?

【问题讨论】:

    标签: python python-3.x telegram-bot python-telegram-bot


    【解决方案1】:

    你有context.user_data dict,它是跨会话持久的,你可以用它来存储所有用户的选择。

    例如

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

    【讨论】:

    • context.user_data 的生命周期是什么?对话结束后会清楚吗?如果用户再次进入同一个入口点,它会在那里吗?
    猜你喜欢
    • 2021-02-02
    • 2021-12-06
    • 2022-12-15
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 2013-02-18
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多