Почему не выходит получить данные из context.user_data[]( получаю None) используя ConversationHandler в python-telegram-bot
недавно начал изучать python-telegram-bot. Смотря примеры в https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.py было решено написать что-то своё, вот что получилось:
import re
from telegram import Update, InlineKeyboardMarkup
from telegram.ext import (
Application,
MessageHandler,
filters,
CallbackQueryHandler,
ConversationHandler,
ContextTypes,
CallbackContext,
)
from text_const import *
from utils.helpers import *
user_data = {}
FULLNAME, EMAIL, NOTES, COMPANIES = range(4)
async def cancel_deal(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Bye!")
return ConversationHandler.END
async def request_fullname_for_deal_handle(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(STATE_FOR_NOTES_WHEN_AUTH,
parse_mode='HTML')
return FULLNAME
async def first_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
answer = update.message.text
if answer.lower() in [CANCEL_HANDLE]:
await cancel_deal(update, context)
return ConversationHandler.END
elif len(answer.split()) != 3:
await update.message.reply_text(NOT_CORRECT_FIO_STATE_TO_DEAL,
parse_mode='HTML')
return FULLNAME
context.user_data['fullname'] = f'{answer}'
await update.message.reply_text(STATE_FOR_EMAIL,
parse_mode='HTML')
return EMAIL
async def second_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
answer = update.message.text
email = answer.strip()
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
await update.message.reply_text(NOT_CORRECT_EMAIL_STATE_TO_DEAL,
parse_mode='HTML')
return EMAIL
context.user_data['email'] = f'{answer}'
await update.message.reply_text(STATE_FOR_NOTES,
parse_mode='HTML')
return NOTES
async def third_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
answer = update.message.text
context.user_data['notes'] = f'{answer}'
db = await init_firebase()
companies_ref = db.collection("comp").stream()
inline_keyboard, callback_data_list = await create_inline_keyboard(comp_ref)
await update.message.reply_text(STATE_FOR_CHOICE_COMPANY_AUTH,
parse_mode='HTML',
reply_markup=inline_keyboard)
print(f"fio after input: {context.user_data.get('fullname')}")
print(f"email after input: {context.user_data.get('email')}")
print(f"Notes after input: {context.user_data.get('notes')}")
return COMPANIES
async def fourth_response(update: Update, context: ContextTypes.DEFAULT_TYPE):
db = await init_firebase()
company_ref = db.collection("comp").document(update.callback_query.data)
client_ref = db.collection("client").where("telegram_id", "==", update.callback_query.message.chat.id).stream()
for client in client_ref:
if client.to_dict().get('tenant_id').id == update.callback_query.data:
pass
else:
context.user_data["comp"] = company_ref
else:
context.user_data["comp"] = company_ref
col_ref = db.collection("crm").where("tenant", "==", comp_ref).stream()
# Format the output
companies_info = f"Companies: {context.user_data.get('companies')}"
notes_info = f"Notes: {context.user_data.get('notes')}"
notess_info = f"fio: {context.user_data.get('fullname')}"
notesss_info = f"email: {context.user_data.get('email')}"
# Collecting CRM settings information
crm_settings_info = "CRM Settings:\n"
for doc in col_ref:
crm_settings_info += f"- {doc.id}: {doc.to_dict()}\n"
# Combine all information into a single message
final_message = f"{notes_info}\n{companies_info}\n{crm_settings_info}\n{notess_info}\n{notesss_info}"
await update.callback_query.message.reply_text(final_message)
return ConversationHandler.END
# FSM
conv_handler = ConversationHandler(
entry_points=
[MessageHandler(filters.Regex(f"^{REQUEST_FULLNAME_FOR_DEAL_HANDLE}$"), request_fullname_for_deal_handle)],
states={
FULLNAME: [MessageHandler(filters.TEXT, first_response)],
EMAIL: [MessageHandler(filters.TEXT, second_response)],
NOTES: [MessageHandler(filters.TEXT, third_response)],
COMPANIES: [CallbackQueryHandler(fourth_response)]
},
fallbacks=[MessageHandler(filters.Regex(f"^{CANCEL_HANDLE}$"), cancel_deal)]
)
Извините, что внёс однотипные функ в код.
В данных строках:
print(f"fio after input: {context.user_data.get('fullname')}")
print(f"email after input: {context.user_data.get('email')}")
print(f"Notes after input: {context.user_data.get('notes')}")
Получаем такой ответ:
fio after input: None # test test test
email after input: None # [email protected]
Notes after input: test # test
Я воожу всегда test , однако получаю None
При получении callbackquery, последнего state, получаю сообщение от бота:
Notes: None
Companies: <google.cloud.firestore_v1.document.DocumentReference object at
...>
CRM Settings:
- ...: {'tenant':
<google.cloud.firestore_v1.document.DocumentReference object at ...>,
'col': []}
fio: None
email: None
Почему не выходит корректно получить context.user_data[] в следующем состоянии или по выходу из него?