Python aiogram:状态开关

Python aiogram: state switch

我正在学习 aiogram,并尝试获取一些消息作为函数调用的参数。正如我从网上了解到的那样,我应该使用状态机

首先我要求一些参数并改变状态,以捕捉下一条消息

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

接下来我尝试在我处于另一个状态时捕获任何消息

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

更新:这是我的实用程序文件

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

但是第二个 message_handler 从未被调用 [TG截图][1] [1]: https://i.stack.imgur.com/81edC.png

也许我对状态机的理解有误,但在示例课程中一切正常

aiogram 中有 StatesGroup Class,这样重写你的代码就可以了

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 将 StatesGroup 用于 FSM