From 68a4a7a4aa5566cc5599b94d9ed4c179d492b12d Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Wed, 15 Nov 2017 18:45:39 +0200 Subject: [PATCH] Add ctx module. Aliases for keys in execution context. --- aiogram/dispatcher/ctx.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 aiogram/dispatcher/ctx.py diff --git a/aiogram/dispatcher/ctx.py b/aiogram/dispatcher/ctx.py new file mode 100644 index 00000000..f1ecce68 --- /dev/null +++ b/aiogram/dispatcher/ctx.py @@ -0,0 +1,39 @@ +from . import Bot +from .. import types +from ..dispatcher import Dispatcher, FSMContext, MODE, UPDATE_OBJECT +from ..utils import context + + +def _get(key, default=None, no_error=False): + result = context.get_value(key, default) + if not no_error and result is None: + raise RuntimeError(f"Context is not configured for '{key}'") + return result + + +def get_bot() -> Bot: + return _get('bot') + + +def get_dispatcher() -> Dispatcher: + return _get('dispatcher') + + +def get_update() -> types.Update: + return _get(UPDATE_OBJECT) + + +def get_mode() -> str: + return _get(MODE, 'unknown') + + +def get_chat() -> int: + return _get('chat', no_error=True) + + +def get_user() -> int: + return _get('user', no_error=True) + + +def get_state() -> FSMContext: + return get_dispatcher().current_state()