Finite State Machine in Aiogram 2 for Telegram Bots

Viewed 15

There is the following situation, in my bot there is a registration of a new user after the /start command, and after it a person can press the /next command and start searching for an interlocutor. And everything will be ok. But if I reload the bot, the user will not be able to get to the same State as after registration.

Is it possible to somehow set the initial state in aiogram ?

And yeah, is there a default state in aiogram states?

1 Answers

If I got it right, You need to persist state between sessions of your application running. Databases exist just for that. I personally like to create a huge enum with all possible dialogue states and deside on next reaction from data called back from user.

enum {
    USER_SET_NAME,
    USER_SET_EMAIL,
    USER_REGISTERED
}

void handle_update(update) {
    current_state = load_from_db(chatId);

    if (current_state == USER_SET_NAME) {
        ask_for_email();
        save_to_db(USER_SET_EMAIL);
        return;
    }

    if (current_state == USER_SET_EMAIL) {
        end_registration();
        save_to_db(USER_REGISTERED);
        return;        
    }
}
Related