Why can’t I get data from context.user_data[] (I get None) using ConversationHandler in python-telegram-bot

I recently started learning python-telegram-bot. Looking at the example in https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot2.py it was decided to write something, this is what happened:

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)]
)

Sorry that the code includes similar functions.

In these lines:

 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')}")

We get this answer:

fio after input: None # test test test
email after input: None # [email protected]
Notes after input: test # test

When receiving callbackquery, the last state, I receive a message from the bot:

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

Why can’t I get context.user_data[] correctly in the next state or upon exiting it? Provided that the data from the last state (received via callback) works correctly

New contributor

Dmitri Supov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật