I'm working on a Telegram bot using the aiogram library, and I'm encountering an issue with the FSM (Finite State Machine) handling. The problem is that after a user sends a request to add a friend, they are supposed to set a nickname for their friend. However, instead of processing the nickname, the bot just treats the next message as a regular message and does not save the nickname. When a user sends a friend request, the bot asks for the friend’s nickname after receiving the target_id and stores it in the FSM state. But when the user sends the nickname, the bot doesn't process it as intended. It seems to treat the nickname as a regular message instead of storing it.
Here is the flow I'm trying to implement:
- The user sends a request to add a friend.
- The bot stores the target_id in FSM state.
- The bot then asks the user for a nickname.
- The user responds with a nickname, and the bot should store it in the database for the friend.
But the issue is that when the user sends the nickname, the bot reads it as a general message and does not associate it with the friend being added.
@dp.message(Form.add_friend)
async def process_friend_request(message: Message, state: FSMContext):
# Bot asks for a nickname after receiving target_id
await state.update_data(target_id=message.text)
await message.answer("✅ Friend added! Now, please provide their nickname.")
@dp.message(Form.set_nickname_requester)
async def handle_requester_nickname(message: Message, state: FSMContext):
# Bot processes nickname but treats message as regular text
data = await state.get_data()
target_id = data.get('target_id')
if target_id:
# Here we need to update friend's nickname but it's treated as regular message
update_friend_name(user_id=message.from_user.id, friend_id=target_id, nickname=message.text.strip())
await message.answer(f"✅ Friend's nickname saved: {message.text}")
else:
await message.answer("❌ Error: target_id is missing!")
Expected Behavior:
After the user sends the friend request, the bot should ask for a nickname.
When the user sends the nickname, the bot should save it as the nickname for the added friend.
Steps Taken:
I have verified that the state is being updated correctly with target_id, but the second message (the nickname) is treated as a regular message, and the bot does not associate it with the target_id. I tried adding additional state checks, but the problem persists.
Actual Behavior:
When the user sends the nickname, it is treated as a regular message, and the bot does not process it as the intended nickname for the friend.
The FSM is not properly associating the nickname with the correct target_id.
Questions:
Why is the nickname not being processed as part of the FSM flow?
How can I ensure the bot recognizes the user's response as the nickname for the friend and not as a regular message?
Are there specific FSM transitions I should handle to make sure the nickname is linked with the correct target_id?