In my Aiogram router code I have several handlers that check the user's text against the buttons text translated by gettext
module:
@router.message(F.text == gettext("Settings"))
async def view_settings(message: Message):
...
In the beginning of the code I set up the gettext
function default value:
import gettext as gt
gettext = gt.translation("ru", "translations", languages=["ru"]).gettext
which returns the function for translating buttons text into Russian.
Every handler works fine until user set up their language to another language like English or Spanish:
gettext = gt.translation("en", "translations", languages=["en"]).gettext
The user's language is not Russian anymore but the handlers still compare user's text to buttons text that was translated into the first initiated language, the Russian.
Is there any way to recalculate gettext
function value in the handlers every time when Aiogram dispatcher decides a handler to call? I'll say in advance, don't suggest switching to inline-buttons.
P.S. I would be glad to make a single @router.message(F.text)
handler where I would check the text alternately via if-else, but because I need to use a FSM in the handlers arguments, this option is not suitable.
The full code that has the issue (some unimportant things were removed to boost the readability):
import gettext as gt
from aiogram import F, Router
from aiogram.types import Message
from aiogram.utils.keyboard import ReplyKeyboardBuilder
gettext = gt.translation("ru", "translations", languages=["ru"]).gettext
router = Router()
@router.message(F.text == "English")
async def change_to_english_language(message: Message):
global gettext
gettext = gt.translation("en", "translations", languages=["en"]).gettext
await message.answer(gettext("Now your language is English"))
@router.message(F.text == gettext("Settings"))
async def view_settings(message: Message):
builder = ReplyKeyboardBuilder()
builder.button(text=gettext("Language"))
builder.button(text=gettext("Preferred name"))
await message.answer(gettext("What do you want to set up?"),
reply_markup=builder.as_markup(resize_keyboard=True))
I have solved my issue, there's a way to use lambda functions after all:
@router.message(F.text, F.func(lambda msg: msg.text == gettext("Settings")))
async def view_settings(message: Message):
builder = ReplyKeyboardBuilder()
builder.button(text=gettext("Language"))
builder.button(text=gettext("Preferred name"))
await message.answer(gettext("What do you want to set up?"),
reply_markup=builder.as_markup(resize_keyboard=True))