Search code examples
telegramsceneaiogram

How to enter the scene passing some data - aiogram


In Aiogram documentation section "Scenes Wizard" described how to register and handle scenes:

class QuizScene(Scene, state="quiz"):
    """
    This class represents a scene for a quiz game.

    It inherits from Scene class and is associated with the state "quiz".
    It handles the logic and flow of the quiz game.
    """

quiz_router = Router(name=__name__)
# Add handler that initializes the scene
quiz_router.message.register(QuizScene.as_handler(), Command("quiz"))

The issue here is how to pass some data to the scene, for example I need to pass string variable to QuizScene class?

I've tried:

quiz_router = Router(name=__name__)
test = "TEST STRING"
# Add handler that initializes the scene
quiz_router.message.register(QuizScene(test).as_handler(), Command("quiz"))

Output error: AttributeError: 'str' object has no attribute 'scene'


Solution

  • The solution appeared to be very simple. If you need some data to be passed to the scene you have to pass it to as_handler() function as argument. In this example we pass test variable:

    quiz_router = Router(name=__name__)
    test = "TEST STRING"
    # Add handler that initializes the scene
    quiz_router.message.register(QuizScene.as_handler(test), Command("quiz"))