ThePigeonKing
ThePigeonKing

Reputation: 54

Python aiogram: state switch

I am learning aiogram, and trying to get some messages as args for funtion call. As I learned from internet I should use State Machine

First I ask for some args and change state, to catch next message

@dp.message_handler(text='Parse', state="*")
async def process_parse_command(msg: types.Message):
    await msg.reply(f"What words to watch for?\n", reply_markup=remove_kb)
    stat = dp.current_state(user=msg.from_user.id)
    await stat.set_state(SomeStates.PARSING_WORD)

Next I try to catch any message when I am on another state

@dp.message_handler(state=SomeStates.PARSING_WORD)
async def process_parse_word(msg: types.Message):
    argument = message.get_args()
    print(argument)
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)

upd: this is my utils file

from aiogram.utils.helper import Helper, HelperMode, ListItem
class SomeStates(Helper):
    mode = HelperMode.snake_case

    MAIN_MENU = ListItem()
    PARSING_WORD = ListItem()
    PARSING_NUMBER = ListItem()
    HELP_MENU = ListItem()
    FAQ_MENU = ListItem()

But second message_handler is never called [TG screenshot][1] [1]: https://i.sstatic.net/81edC.png

Maybe I got something wrong about State Machine, but in the example lesson everything worked

Upvotes: 1

Views: 2958

Answers (1)

Maksim K.
Maksim K.

Reputation: 326

There are StatesGroup Class in aiogram, rewrite your code like this and it works

class SomeStates(StatesGroup):
    MAIN_MENU = State()
    PARSING_WORD = State()
    PARSING_NUMBER = State()
    HELP_MENU = State()
    FAQ_MENU = State()
    

@dp.message_handler(text='Parse', state="*")
async def process_parse_command(msg: types.Message):
    await msg.reply(f"What words to watch for?\n")
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)
    await stat.set_state(SomeStates.PARSING_WORD)


@dp.message_handler(state=SomeStates.PARSING_WORD)
async def process_parse_word(msg: types.Message):
    # there was a mistake here
    # argument = message.get_args() - NameError: name 'message' is not defined
    # argument = msg.get_args() # None is here, better use message.text
    argument = msg.text
    print(argument) 
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)

Aiogram official documentation using StatesGroup for FSM

Upvotes: 3

Related Questions