Refactor Telegram bot code login: unify UI with single message editing

Remove FakeMessage wrapper class and implement consistent message editing
for web app code login flow. User-submitted code is now deleted immediately
and instructions message transforms in-place to show menu, matching the
email login UX pattern.

Changes:
- Remove FakeMessage class from start_command handler
- Use direct edit_message_text for all message updates
- Delete user's code message for cleaner chat interface
- Preserve web_login_message_id in context throughout flow
- Apply same pattern to handle_text_message (8-char code handler)
- Ensure single editable message from instructions to menu

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-12 00:51:28 +02:00
parent 6e6111df18
commit a227a10ca8

View File

@@ -72,37 +72,22 @@ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
text="Conectare cont...", text="Conectare cont...",
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
) )
linking_msg = await context.bot.get_updates() # Dummy, ne interesează doar message_id # IMPORTANT: NU ștergem message_id - îl păstrăm pentru editări ulterioare
# Simulăm un obiect Message pentru a putea folosi .edit_text() mai jos
class FakeMessage:
def __init__(self, chat_id, message_id, bot):
self.chat_id = chat_id
self.message_id = message_id
self._bot = bot
async def edit_text(self, text, reply_markup=None, parse_mode=None):
await self._bot.edit_message_text(
chat_id=self.chat_id,
message_id=self.message_id,
text=text,
reply_markup=reply_markup,
parse_mode=parse_mode
)
linking_msg = FakeMessage(update.effective_chat.id, web_login_msg_id, context.bot)
# Clear message_id din context
context.user_data.pop('web_login_message_id', None)
except Exception as e: except Exception as e:
logger.warning(f"Could not edit web_login message: {e}") logger.warning(f"Could not edit web_login message: {e}")
# Fallback: creează mesaj nou # Fallback: creează mesaj nou dacă editarea a eșuat
linking_msg = await update.effective_chat.send_message( web_login_msg_id = None
"Conectare cont...",
parse_mode=ParseMode.MARKDOWN # Dacă nu avem mesaj de editat, creăm unul nou
) if not web_login_msg_id:
else: # Creează mesaj nou și salvează ID-ul în context pentru editări ulterioare
# Nu există mesaj anterior - creează mesaj nou new_msg = await update.effective_chat.send_message(
linking_msg = await update.effective_chat.send_message(
"Conectare cont...", "Conectare cont...",
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
) )
web_login_msg_id = new_msg.message_id
# Salvează în context pentru consistență
context.user_data['web_login_message_id'] = web_login_msg_id
# Attempt linking # Attempt linking
result = await link_telegram_account(telegram_user, auth_code) result = await link_telegram_account(telegram_user, auth_code)
@@ -141,8 +126,11 @@ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
menu_message = pad_message_for_wide_buttons(menu_text) menu_message = pad_message_for_wide_buttons(menu_text)
await linking_msg.edit_text( # EDIT the login message (same message throughout the flow)
menu_message, await context.bot.edit_message_text(
chat_id=update.effective_chat.id,
message_id=web_login_msg_id,
text=menu_message,
reply_markup=keyboard, reply_markup=keyboard,
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
) )
@@ -151,8 +139,10 @@ async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
else: else:
# Failed linking - EDIT message to show error # Failed linking - EDIT message to show error
await linking_msg.edit_text( await context.bot.edit_message_text(
"Cod invalid sau expirat\n\n" chat_id=update.effective_chat.id,
message_id=web_login_msg_id,
text="Cod invalid sau expirat\n\n"
"Generează un cod nou din aplicația web și trimite:\n" "Generează un cod nou din aplicația web și trimite:\n"
"/start CODUL_TAU", "/start CODUL_TAU",
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
@@ -1306,18 +1296,40 @@ async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE
if len(text) == 8 and text.isalnum(): if len(text) == 8 and text.isalnum():
logger.info(f"Detected potential linking code: {text} from user {telegram_user_id}") logger.info(f"Detected potential linking code: {text} from user {telegram_user_id}")
# Show "linking..." message # ȘTERGE mesajul utilizatorului cu codul (chat curat)
linking_msg = await update.message.reply_text( try:
"Linking contul...\n" await update.message.delete()
"Te rog asteapta..." except Exception as e:
logger.warning(f"Could not delete code message: {e}")
# Check dacă există mesaj de editat din "Login din Web App"
web_login_msg_id = context.user_data.get('web_login_message_id')
if web_login_msg_id:
# EDITEAZĂ mesajul existent cu instrucțiunile
try:
await context.bot.edit_message_text(
chat_id=update.effective_chat.id,
message_id=web_login_msg_id,
text="Conectare cont...",
parse_mode=ParseMode.MARKDOWN
) )
except Exception as e:
logger.warning(f"Could not edit web_login message: {e}")
# Fallback: creează mesaj nou
web_login_msg_id = None
# Dacă nu există mesaj de editat, creează unul nou
if not web_login_msg_id:
linking_msg = await update.effective_chat.send_message(
"Conectare cont...",
parse_mode=ParseMode.MARKDOWN
)
web_login_msg_id = linking_msg.message_id
# Attempt linking # Attempt linking
result = await link_telegram_account(telegram_user, text) result = await link_telegram_account(telegram_user, text)
# Delete "linking..." message
await linking_msg.delete()
if result: if result:
# Success! # Success!
username = result['username'] username = result['username']
@@ -1331,35 +1343,32 @@ async def handle_text_message(update: Update, context: ContextTypes.DEFAULT_TYPE
from app.bot.menus import create_main_menu, pad_message_for_wide_buttons from app.bot.menus import create_main_menu, pad_message_for_wide_buttons
keyboard = create_main_menu(company_name, company_cui, is_authenticated=True) keyboard = create_main_menu(company_name, company_cui, is_authenticated=True)
# Single welcome message with menu # Create menu text
if company_name: if company_name:
welcome_text = ( menu_text = f"{company_name}"
f"**Cont conectat cu succes**\n\n"
f"Bun venit, **{username}**!\n\n"
f"{company_name}"
)
else: else:
welcome_text = ( menu_text = "Selectează o companie pentru a continua"
f"**Cont conectat cu succes**\n\n"
f"Bun venit, **{username}**!\n\n"
f"Selectează o companie pentru a continua"
)
welcome_message = pad_message_for_wide_buttons(welcome_text) menu_message = pad_message_for_wide_buttons(menu_text)
await update.message.reply_text( # EDIT the same message to show menu (no new messages!)
welcome_message, await context.bot.edit_message_text(
chat_id=update.effective_chat.id,
message_id=web_login_msg_id,
text=menu_message,
reply_markup=keyboard, reply_markup=keyboard,
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
) )
logger.info(f"User {telegram_user_id} successfully linked to {username} via direct code input") logger.info(f"User {telegram_user_id} successfully linked to {username} via direct code input")
else: else:
# Failed linking # Failed linking - EDIT the same message to show error
await update.message.reply_text( await context.bot.edit_message_text(
"**Cod invalid sau expirat**\n\n" chat_id=update.effective_chat.id,
"Genereaza un cod nou din aplicatia web si trimite-l direct.\n\n" message_id=web_login_msg_id,
"Codul expira in 15 minute.", text="Cod invalid sau expirat\n\n"
"Generează un cod nou din aplicația web și trimite-l direct.\n\n"
"Codul expiră în 15 minute.",
parse_mode=ParseMode.MARKDOWN parse_mode=ParseMode.MARKDOWN
) )