pythonfsmaiogram

takes no arguments in FSM step


One-step FSM Error: Town() takes no arguments

@weather_router.message(Command("weather"))
class Town(StatesGroup):
    town = State()
async def town(message: Message, state: FSMContext):
    await message.answer(f"{message.from_user.first_name}, введи город")
    await state.set_state(Town.town)
async def townn(message: Message):
    await message.answer(f"Ваш город\n{message.text}")

I want bot to handle users “town” and send it him back by text message using FSM


Solution

    1. remove "Town" states group from under decorator, because it decorates a group of states, not a message handler
    2. decorate "townn" function with state filter: @weather_router.message(Town.town)
    3. add await state.clear() to "townn" function to clear FSM context

    code:

    class Town(StatesGroup):
        town = State()
    
    @weather_router.message(Command('weather'))
    async def town(message: Message, state: FSMContext):
        await state.set_state(Town.town)
    
        await message.answer(f"{message.from_user.first_name}, введи город")
    
    @weather_router.message(Town.town)
    async def townn(message: Message, state: FSMContext):
        await message.answer(f"Ваш город\n{message.text}")
    
        await state.clear()