Yed*_*fir 4 python python-3.x python-telegram-bot telegram-bot
我正在构建一个电报机器人。
我的机器人的功能之一要求机器人询问用户以在选项之间进行选择。听到的是我查询用户的代码
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
)
Run Code Online (Sandbox Code Playgroud)
如您所见,在函数中user_picked_store我需要保存用户选择(只有在用户选择所有信息后我才能保存在数据库中)。因此,我需要访问用户所做的所有选择,我想将其存储在函数外部的对象中,以便所有函数都可以使用它,但是如果同时发出多个请求,则此解决方案将不起作用(每个请求都会覆盖另一个请求)。
有没有办法为对话的每个实例保存状态?
每个对话都有会话 ID 吗?
小智 13
您有context.user_data一个在整个对话中持久存在的字典,您可以使用它来存储所有用户选择。
例如
query = update.callback_query
querydata = query.data
context.user_data["key"] = querydata
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7832 次 |
| 最近记录: |