Skip to content

I18n — Advanced Localization

The localization system in codex-bot is built on top of Project Fluent and provides tools for efficient translation management in complex, multi-module projects.


💎 Key Benefits

1. Decentralized Storage

Unlike traditional systems where all translations reside in a single massive file, codex-bot allows you to break them down into many small .ftl files. You can keep translations directly inside feature folders, which significantly simplifies code maintenance.

2. Path-based Isolation (Hashing)

At bot startup, the engine automatically compiles all discovered files into an isolated temporary directory. - Mechanics: The path to the temporary folder is generated as MD5(absolute_project_path). - Why it matters: This ensures that if multiple different bots are running on the same server, they will not conflict or overwrite each other's translations in the system's /tmp folder.

3. Automatic Compilation

There is no need to manually run build scripts. The compile_locales() method is called automatically during bot initialization, merging all scattered .ftl files into unified dictionaries for each language.


✍️ How to Use

Defining Translations

Create a greeting.ftl file within your feature directory:

# greeting.ftl
hello-user = Hello, {$name}! Welcome.

Using in Code

Thanks to the I18nMiddleware, the translation context is available globally or via the request context:

# Inside an orchestrator or handler
from aiogram_i18n import I18nContext

async def render_content(self, payload, director: Director):
    # Accessed via container or request context
    i18n: I18nContext = director.container.i18n
    text = i18n.get("hello-user", name="Alice")

    return ViewResultDTO(text=text)

⚙️ Project Configuration

In your core/factory.py file, the compiler and middleware are linked as follows:

from codex_bot.engine.i18n import compile_locales

# 1. Compile all locales into an isolated folder
locales_path = compile_locales(pathlib.Path("resources/locales"))

# 2. Connect to aiogram
i18n_middleware = I18nMiddleware(
    core=FluentRuntimeCore(path=locales_path),
    manager=FSMContextI18nManager(),
)