### Basic Middleware Setup Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates the basic setup for integrating the I18nMiddleware into an aiogram application. This is a common starting point for internationalization. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup(I18nMiddleware(bot=bot)) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Custom Configurations Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows a basic example of how to provide custom configurations to the I18nMiddleware, allowing for more tailored internationalization setups. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores import FluentRuntimeCore async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup( I18nMiddleware( bot=bot, # Use a custom core implementation core=FluentRuntimeCore(path='locales/') ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Jinja2Core Initialization Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Shows how to initialize Jinja2Core with a path, default locale, and a custom Jinja2 environment configured for autoescaping. This setup is useful for web contexts. ```python from aiogram_i18n.cores.jinja2_core import Jinja2Core from jinja2 import Environment, autoescape core = Jinja2Core( path="locales/{locale}", default_locale="en", environment=Environment(autoescape=autoescape.select_autoescape()) ) ``` -------------------------------- ### GNUTextCore Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md An example of initializing GNUTextCore with a path and default locale. ```python from aiogram_i18n.cores.gnu_text_core import GNUTextCore core = GNUTextCore( path="locales/{locale}/LC_MESSAGES", default_locale="en" ) ``` -------------------------------- ### Install FluentRuntimeCore Source: https://github.com/aiogram/i18n/blob/dev/README.md Install the fluent.runtime package if you plan to use FluentRuntimeCore. ```bash pip install fluent.runtime ``` -------------------------------- ### FluentRuntimeCore Initialization Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md An example demonstrating how to instantiate FluentRuntimeCore with a specific path, default locale, and error handling configuration. ```python from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore core = FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES", default_locale="en", raise_key_error=False ) ``` -------------------------------- ### Install FluentCompileCore Source: https://github.com/aiogram/i18n/blob/dev/README.md Install the fluent_compiler package if you plan to use FluentCompileCore. ```bash pip install fluent_compiler ``` -------------------------------- ### FluentCompileCore Initialization Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Provides an example of how to initialize the FluentCompileCore with a specified path and default locale. Ensure the path correctly points to your .ftl message files. ```python from aiogram_i18n.cores.fluent_compile_core import FluentCompileCore core = FluentCompileCore( path="locales/{locale}/LC_MESSAGES", default_locale="en" ) ``` -------------------------------- ### FluentRuntimeCore Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md An example of initializing FluentRuntimeCore with a specific path, default locale, error handling, and locale mapping. ```python from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore core = FluentRuntimeCore( path="translations/{locale}/messages", default_locale="en", raise_key_error=False, locales_map={ "en-GB": "en", "pt-BR": "pt", } ) ``` -------------------------------- ### Basic aiogram_i18n Setup Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/13-index.md Demonstrates the basic setup for aiogram_i18n middleware, including configuring the translation core and locale manager. Ensure you have the necessary dependencies installed. ```python from aiogram import Dispatcher, Bot from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.fsm import FSMManager bot = Bot(token="YOUR_TOKEN") dp = Dispatcher() middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=FSMManager(), default_locale="en" ) middleware.setup(dp) ``` -------------------------------- ### Configuration Reference: Example Configurations Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt Presents example configurations for the aiogram-i18n library, illustrating various parameter settings. ```python # Example configuration snippet (conceptual) # config = { # "default_locale": "en", # "locales": ["en", "ru", "es"], # "path": "locales/{{locale}}/LC_MESSAGES/messages.po" # } ``` -------------------------------- ### Aiogram i18n Middleware Integration Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/2-i18n-middleware.md Example demonstrating how to integrate and use the I18nMiddleware in an aiogram bot. It shows setup with FluentRuntimeCore and FSMManager. ```python import asyncio from contextlib import suppress from aiogram import Router, Dispatcher, Bot from aiogram.types import Message from aiogram.filters import CommandStart from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.fsm import FSMManager router = Router() @router.message(CommandStart()) async def start_handler(message: Message, i18n: I18nContext): text = i18n.get("greeting", user_name=message.from_user.first_name) await message.reply(text) async def main(): bot = Bot(token="42:ABC") middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=FSMManager(), default_locale="en" ) dp = Dispatcher() dp.include_router(router) middleware.setup(dispatcher=dp) await dp.start_polling(bot) if __name__ == "__main__": with suppress(KeyboardInterrupt): asyncio.run(main()) ``` -------------------------------- ### Jinja2 File Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md An example of a Jinja2 template file for translations. ```jinja2 Hello {{ user_name }}! {% if is_premium %} Premium features unlocked! {% endif %} You have {{ item_count }} items. ``` -------------------------------- ### Install aiogram-i18n with FluentRuntimeCore Source: https://github.com/aiogram/i18n/blob/dev/docs/index.md Install aiogram-i18n with the Fluent.runtime backend support. ```bash pip install aiogram-i18n[runtime] ``` -------------------------------- ### Button Creation Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows a simple example of creating an inline keyboard button with specific text and callback data using the InlineKeyboardBuilder. ```python from aiogram import types from aiogram_i18n.keyboards import InlineKeyboardBuilder async def get_simple_keyboard(message: types.Message): builder = InlineKeyboardBuilder(message=message) # Creating a button with static text and a callback data builder.button(text='Click Me', callback_data='simple_click') return builder.as_markup() ``` -------------------------------- ### FSMManager Usage Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/7-locale-managers.md Demonstrates setting up I18nMiddleware with FSMManager and RedisStorage for persistent locale storage. ```python from aiogram import Dispatcher from aiogram.fsm.storage.redis import RedisStorage from aiogram_i18n import I18nMiddleware from aiogram_i18n.managers.fsm import FSMManager # Redis storage for persistence storage = RedisStorage.from_url("redis://localhost:6379") dispatcher = Dispatcher(storage=storage) middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=FSMManager(key="user_locale", default_locale="en") ) middleware.setup(dispatcher=dispatcher) ``` -------------------------------- ### Fluent File Example (messages.ftl) Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md An example of a Fluent resource file structure for translations. ```ftl # messages.ftl app-name = My Awesome Bot ## Navigation menu-start = Start menu-help = Help menu-settings = Settings ## Messages greeting = Hello { $user_name }! welcome-premium = Welcome back, premium user! ## Plurals item-count = { $count -> [0] No items [1] One item *[other] { $count } items } ``` -------------------------------- ### MagicProxy Constructor Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/11-magic-proxy.md Demonstrates how to instantiate MagicProxy with a callable and a key separator. ```python from aiogram_i18n.utils.magic_proxy import MagicProxy from aiogram_i18n import LazyProxy def build_key(*args, **kwargs) -> LazyProxy: return LazyProxy(*args, **kwargs) proxy = MagicProxy(call=build_key, key_separator="-") ``` -------------------------------- ### Locale Managers: Custom Implementation Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt Shows an example of creating a custom locale manager for specific persistence or lifecycle needs. ```python # Example of a custom locale manager (conceptual) # from aiogram_i18n.locale_manager import LocaleManager # class MyLocaleManager(LocaleManager): # async def get_locale(self, *args, **kwargs) -> str: # # Custom logic to determine locale # return "en" ``` -------------------------------- ### Install aiogram-i18n with FluentCompileCore Source: https://github.com/aiogram/i18n/blob/dev/docs/index.md Install aiogram-i18n with the fluent-compiler backend support. ```bash pip install aiogram-i18n[compiler] ``` -------------------------------- ### aiogram-i18n Usage Example Source: https://github.com/aiogram/i18n/blob/dev/docs/index.md A comprehensive example demonstrating the setup and usage of aiogram-i18n with FluentRuntimeCore, including message handling and internationalization context. ```python import asyncio from contextlib import suppress from logging import INFO, basicConfig from typing import Any from aiogram import Bot, Dispatcher, Router from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message from aiogram_i18n import I18nContext, I18nMiddleware, LazyProxy from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.lazy.filter import LazyFilter from aiogram_i18n.types import ( KeyboardButton, ReplyKeyboardMarkup, ) # you should import mutable objects from here if you want to use LazyProxy in them router = Router(name=__name__) rkb = ReplyKeyboardMarkup( keyboard=[[KeyboardButton(text=LazyProxy("help"))]], resize_keyboard=True # or L.help() ) @router.message(CommandStart()) async def cmd_start(message: Message, i18n: I18nContext) -> Any: name = message.from_user.mention_html() return message.reply( text=i18n.get("hello", user=name), reply_markup=rkb # or i18n.hello(user=name) ) @router.message(LazyFilter("help")) async def cmd_help(message: Message) -> Any: return message.reply(text="-- " + message.text + " --") async def main() -> None: basicConfig(level=INFO) bot = Bot("42:ABC", default=DefaultBotProperties(parse_mode=ParseMode.HTML)) i18n_middleware = I18nMiddleware(core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES")) dp = Dispatcher() dp.include_router(router) i18n_middleware.setup(dispatcher=dp) await dp.start_polling(bot) if __name__ == "__main__": with suppress(KeyboardInterrupt): asyncio.run(main()) ``` -------------------------------- ### Configuration Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/README.md Provides an example of configuring the `FluentRuntimeCore` with a locale path, default locale, and error handling settings. ```APIDOC ## Configuration See: [Configuration Reference](14-configuration-reference.md) ```python core = FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES", default_locale="en", raise_key_error=False, locales_map={"en-GB": "en"} ) ``` ``` -------------------------------- ### Development Memory Storage Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Illustrates setting up the I18nMiddleware with in-memory storage, suitable for development and testing purposes. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup( I18nMiddleware( bot=bot, # Use MemoryManager for development locale_manager=MemoryManager() ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### GNUTextCore Initialization and Pluralization Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Demonstrates initializing GNUTextCore and using its `nget` method for plural forms. This example shows how to handle singular and plural messages based on a count. ```python from aiogram_i18n.cores.gnu_text_core import GNUTextCore core = GNUTextCore( path="locales/{locale}/LC_MESSAGES", default_locale="en" ) # Plural support msg = core.nget("one_file", "many_files", 5) ``` -------------------------------- ### MagicProxy __call__ Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/11-magic-proxy.md Shows how MagicProxy builds the final key and calls the provided callable with arguments. ```python def build_lazy(key, locale=None, **kwargs): return f"LazyProxy('{key}')" proxy = MagicProxy(build_lazy) result = proxy.menu.start() # Builds key: "menu-start" # Calls: build_lazy("menu-start", None) # Returns: "LazyProxy('menu-start')" result = proxy.dialog.error.title(locale="fr", user="Bob") # Builds key: "dialog-error-title" # Calls: build_lazy("dialog-error-title", "fr", user="Bob") ``` -------------------------------- ### Fluent Translation File Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/13-index.md Example of a translation file in Fluent (.ftl) format, demonstrating simple strings and parameterized messages. ```fluent greeting = Hello! welcome = Welcome { $user_name }! menu-start = Start menu-help = Help ``` -------------------------------- ### Locale Switching Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates how to programmatically switch the user's locale within a handler, for example, in response to a command. ```python from aiogram import types from aiogram.dispatcher.filters import Command @dp.message_handler(Command('set_locale')) async def set_locale_handler(message: types.Message): # Example: switch locale to 'es' (Spanish) await message.from_user.i18n.set_locale('es') await message.answer(message.from_user.i18n.locale_changed) ``` -------------------------------- ### I18nMiddleware Configuration: Multi-Language with Fallback Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Example demonstrating multi-language support with locale fallbacks using FSMManager and FluentRuntimeCore. ```python middleware = I18nMiddleware( core=FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES", default_locale="en", locales_map={ "en-GB": "en", "en-US": "en", "pt-BR": "pt", "zh-Hans": "zh", } ), manager=FSMManager(key="user_locale"), default_locale="en" ) ``` -------------------------------- ### Production Redis Configuration Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows how to configure the I18nMiddleware with Redis for production environments, utilizing persistent storage for locale data. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.redis import RedisStorage2 from aiogram_i18n import I18nMiddleware async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=RedisStorage2(host='localhost', port=6379, db=5)) dp.middleware.setup( I18nMiddleware( bot=bot, # Use RedisManager for production locale_manager=RedisManager(storage=dp.storage) ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Create BotCommand with LazyProxy Fields Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/10-types.md Example of creating a list of BotCommands with lazy support for command and description. ```Python from aiogram_i18n import LazyProxy from aiogram_i18n.types import BotCommand commands = [ BotCommand( command=LazyProxy("cmd.start"), description=LazyProxy("cmd.start_desc") ) ] ``` -------------------------------- ### Install aiogram-i18n Source: https://github.com/aiogram/i18n/blob/dev/docs/index.md Install the base aiogram-i18n package without any specific backends. ```bash pip install aiogram-i18n ``` -------------------------------- ### Example of Additional Buttons with LanguageInlineMarkup Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Demonstrates how to use LanguageInlineMarkup with additional buttons for language selection. ```python additional = [ [InlineKeyboardButton(text="Settings", callback_data="settings")] ] lang_kb = LanguageInlineMarkup( key="language.name", keyboard=additional ) ``` -------------------------------- ### Install aiogram_i18n Source: https://github.com/aiogram/i18n/blob/dev/README.md Install the core aiogram_i18n library using pip. ```bash pip install aiogram_i18n ``` -------------------------------- ### MemoryManager Usage Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/7-locale-managers.md Demonstrates the simplest implementation of a locale manager using MemoryManager with I18nMiddleware. ```python from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.memory import MemoryManager middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=MemoryManager(default_locale="en") ) ``` -------------------------------- ### Complete Integration Example for Language Selection Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/9-language-inline-keyboard.md A full example showcasing the integration of LanguageInlineMarkup within an aiogram bot. It includes setting up the router, creating the language keyboard, and handling the CommandStart to display the welcome message and language selection options. ```python from aiogram import Router, F from aiogram.types import Message, CallbackQuery from aiogram.filters import CommandStart from aiogram_i18n import I18nMiddleware, I18nContext from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.fsm import FSMManager from aiogram_i18n.utils.language_inline_keyboard import LanguageInlineMarkup router = Router() # Create language keyboard lang_keyboard = LanguageInlineMarkup( key="language.name", hide_current=False ) @router.message(CommandStart()) async def start_handler(message: Message, i18n: I18nContext): text = i18n.get("welcome") keyboard = lang_keyboard.reply_markup() await message.reply( text=text, reply_markup=keyboard ) ``` -------------------------------- ### GNU gettext Translation File Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/13-index.md Example of a translation file in GNU gettext (.po) format, showing basic message IDs and their translations. ```po msgid "greeting" msgstr "Hello!" msgid "welcome" msgstr "Welcome %s!" ``` -------------------------------- ### Install aiogram-i18n with GNU gettext Source: https://github.com/aiogram/i18n/blob/dev/docs/index.md Install aiogram-i18n with the GNU gettext backend support. ```bash pip install aiogram-i18n[gettext] ``` -------------------------------- ### Setup and Integration: i18n-middleware.md Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt Information on setting up and configuring the i18n middleware for dispatcher integration, including lifecycle management and startup callbacks. ```APIDOC ## Setup and Integration: i18n-middleware.md ### Description This section guides users through the setup and configuration of the i18n middleware. It explains how to integrate it with the dispatcher, manage its lifecycle, and utilize startup callbacks. ### Key Topics - Setup and configuration - Dispatcher integration - Lifecycle management - Startup callbacks ``` -------------------------------- ### Custom Managers Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates how to implement and use custom locale managers, providing flexibility in how user locales are stored and retrieved. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware from aiogram_i18n.managers import BaseManager # Define a custom manager (example) class MyCustomManager(BaseManager): async def get_locale(self, user_id: int) -> str: # Custom logic for getting locale return 'en' async def set_locale(self, user_id: int, locale: str): # Custom logic for setting locale pass async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup( I18nMiddleware( bot=bot, locale_manager=MyCustomManager() ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Jinja2 Translation File Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/13-index.md Example of a translation file in Jinja2 (.j2) format, illustrating basic string interpolation and conditional logic. ```jinja2 Hello {{ user_name }}! {% if is_admin %}Admin Panel{% endif %} ``` -------------------------------- ### I18nMiddleware Configuration: Production (Redis with FSM) Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Example of configuring I18nMiddleware for production using Redis for storage and FluentCompileCore. ```python from aiogram.fsm.storage.redis import RedisStorage from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores.fluent_compile_core import FluentCompileCore from aiogram_i18n.managers.redis import RedisManager from redis.asyncio import Redis redis = Redis.from_url("redis://localhost:6379") middleware = I18nMiddleware( core=FluentCompileCore( path="locales/{locale}/LC_MESSAGES", default_locale="en", raise_key_error=False ), manager=RedisManager( redis=redis, default_locale="en" ), default_locale="en", key_separator="-" ) ``` -------------------------------- ### Translation Cores: Custom Function Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt Provides an example of implementing a custom translation function within a translation core. ```python # Example of a custom translation function (conceptual) # class CustomCore(TranslationCore): # async def get_string(self, key: str, **kwargs) -> str: # # Custom logic here # return f"Custom: {key}" ``` -------------------------------- ### Setup I18nMiddleware Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/README.md Integrates the I18nMiddleware with the aiogram dispatcher. This middleware handles the setup of translation cores and locale managers for per-request i18n context. ```python middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=FSMManager() ) middleware.setup(dispatcher) ``` -------------------------------- ### Language Selection Keyboard Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates building an inline keyboard that allows users to select their preferred language. This uses the LanguageInlineMarkup builder. ```python from aiogram import types from aiogram_i18n.keyboards import LanguageInlineMarkup async def get_language_keyboard(message: types.Message): # Building a keyboard for language selection markup = LanguageInlineMarkup( message=message, callback_data='set_lang_{lang}', current_locale=message.from_user.i18n.locale ).as_markup() return markup ``` -------------------------------- ### Configuration Reference: configuration-reference.md Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt A detailed reference for all configuration options, including parameter tables, example configurations, file structure, and performance tuning tips. ```APIDOC ## Configuration Reference: configuration-reference.md ### Description This section provides a comprehensive reference for all configuration options available in aiogram-i18n. It includes detailed parameter tables, example configurations, guidance on file structure, and tips for performance tuning. ### Configuration Details - All configuration options listed - Parameter tables - Example configurations - File structure guide - Performance tuning ``` -------------------------------- ### Locale Fallback Mapping Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Demonstrates how to configure locale fallback mappings for various translation cores. This example uses FluentRuntimeCore to show how regional variants can fall back to a base language. ```python from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore core = FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES", locales_map={ "en-GB": "en", # British English falls back to English "pt-BR": "pt", # Brazilian Portuguese falls back to Portuguese "zh-Hant": "zh", # Traditional Chinese falls back to Chinese } ) ``` -------------------------------- ### Setup I18n Middleware Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/9-language-inline-keyboard.md Configures the I18nMiddleware with a FluentRuntimeCore for locale message loading and an FSMManager. This middleware must be set up with the dispatcher. ```python from aiogram import Dispatcher from aiogram_i18n import I18nMiddleware from aiogram_i18n.core.fluent import FluentRuntimeCore from aiogram_i18n.managers.fsm import FSMManager # Assuming 'dp' is your initialized Dispatcher instance dp: Dispatcher middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=FSMManager() ) middleware.setup(dispatcher=dp) ``` -------------------------------- ### I18nMiddleware Configuration: Development (In-Memory) Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Example of configuring I18nMiddleware for development using an in-memory locale manager and FluentRuntimeCore. ```python from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.memory import MemoryManager middleware = I18nMiddleware( core=FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES", default_locale="en" ), manager=MemoryManager(default_locale="en"), default_locale="en" ) ``` -------------------------------- ### Middleware Setup and Integration Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/MANIFEST.txt Learn how to set up and integrate the i18n middleware into your aiogram dispatcher for seamless locale handling. ```python # Example of middleware setup (conceptual) # from aiogram import Dispatcher # from aiogram_i18n.middleware import I18nMiddleware # dp = Dispatcher() # dp.update_middleware(I18nMiddleware(I18n("en", "ru"))) ``` -------------------------------- ### Create InlineKeyboardButton with LazyProxy Fields Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/10-types.md Example of creating an InlineKeyboardButton with lazy support for text and callback data. ```Python from aiogram_i18n.types import InlineKeyboardButton, InlineKeyboardMarkup button = InlineKeyboardButton( text=LazyProxy("button.edit"), callback_data=LazyProxy("action.edit") ) keyboard = InlineKeyboardMarkup(inline_keyboard=[[button]]) ``` -------------------------------- ### Custom Functions Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates how to register and use custom functions within the translation context, allowing for dynamic content generation. ```python from aiogram import types from aiogram_i18n.cores import FluentRuntimeCore def get_current_time() -> str: import datetime return datetime.datetime.now().strftime('%H:%M:%S') # Assuming FluentRuntimeCore is used and configured with custom_functions # core = FluentRuntimeCore(path='locales/', custom_functions={'time': get_current_time}) # In a message handler: # await message.answer(message.from_user.i18n.get('current_time_is', time=message.from_user.i18n.get_custom_function('time'))) # Or directly if registered in the core: # await message.answer(message.from_user.i18n.get('current_time_is', time=get_current_time())) ``` -------------------------------- ### ConstManager Setup Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Configure ConstManager for bots operating with a single, constant locale. Useful for single-language bots or development. ```python from aiogram_i18n.managers.const import ConstManager # All users get English manager = ConstManager(default_locale="en") ``` -------------------------------- ### Custom Cores Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Illustrates the concept of using custom translation core implementations, allowing for integration with different translation file formats or services. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware from aiogram_i18n.cores import BaseCore # Define a custom core (example) class MyCustomCore(BaseCore): async def get(self, key: str, **kwargs) -> str: # Custom logic for retrieving translations return f"Custom: {key}" async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup( I18nMiddleware( bot=bot, core=MyCustomCore() ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Example Usage of RedisManager with I18nMiddleware Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/7-locale-managers.md Demonstrates how to set up I18nMiddleware using RedisManager for locale management. Ensure Redis is running and accessible. ```python from redis.asyncio import Redis from aiogram_i18n import I18nMiddleware from aiogram_i18n.managers.redis import RedisManager from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore # Create Redis client redis = Redis.from_url("redis://localhost:6379") middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=RedisManager(redis=redis, default_locale="en") ) middleware.setup(dispatcher=dispatcher) ``` -------------------------------- ### Create KeyboardButton with LazyProxy Text Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/10-types.md Example of creating a KeyboardButton with lazy text support for reply keyboards. ```Python from aiogram_i18n import LazyProxy from aiogram_i18n.types import KeyboardButton, ReplyKeyboardMarkup button = KeyboardButton(text=LazyProxy("button.start")) keyboard = ReplyKeyboardMarkup(keyboard=[[button]]) ``` -------------------------------- ### LazyFactory Usage Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows how to use LazyFactory to create translatable objects, such as inline keyboard buttons, which defer translation until needed. ```python from aiogram import types from aiogram_i18n.keyboards import InlineKeyboardBuilder from aiogram_i18n.lazy_factory import LazyFactory async def get_keyboard(message: types.Message): builder = InlineKeyboardBuilder(message=message) # Using LazyFactory to create translatable button text factory = LazyFactory(message=message) builder.button(text=factory.get('option_1'), callback_data='option_1') builder.button(text=factory.get('option_2'), callback_data='option_2') return builder.as_markup() ``` -------------------------------- ### Chained Attribute Access Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/11-magic-proxy.md Demonstrates how MagicProxy chains attribute accesses to build a key. This is equivalent to a direct call with the fully formed key. ```python from aiogram_i18n.utils.magic_proxy import MagicProxy def show_key(key, locale=None, **kwargs): return f"Key: {key}, Locale: {locale}, Args: {kwargs}" proxy = MagicProxy(show_key) # Simple chain print(proxy.hello()) # "Key: hello, Locale: None, Args: {}" # Nested chain print(proxy.greeting.welcome()) # "Key: greeting-welcome, Locale: None, Args: {}" # With parameters print(proxy.msg.error(locale="fr", code=404)) # "Key: msg-error, Locale: fr, Args: {'code': 404}" # Long chain print(proxy.app.dialog.step.one()) # "Key: app-dialog-step-one, Locale: None, Args: {}" ``` -------------------------------- ### Example Usage of ConstManager with I18nMiddleware Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/7-locale-managers.md Shows how to configure I18nMiddleware with ConstManager. This is suitable for bots that operate in a single language. ```python from aiogram_i18n import I18nMiddleware from aiogram_i18n.managers.const import ConstManager middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES"), manager=ConstManager(default_locale="en") ) ``` -------------------------------- ### Fallback Strategies Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows how to implement fallback strategies for translations, ensuring that a message is always displayed even if the primary translation is missing. ```python from aiogram import types @dp.message_handler() async def fallback_handler(message: types.Message): # Using .get() with a fallback string directly await message.answer( message.from_user.i18n.get( 'specific_message', default='A default message if specific_message is not found' ) ) ``` -------------------------------- ### Locale Mapping Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows how to map different user-provided locale identifiers to canonical locale keys used by the library. ```python from aiogram import Bot, Dispatcher from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram_i18n import I18nMiddleware async def main(): bot = Bot(token="YOUR_BOT_TOKEN") dp = Dispatcher(bot, storage=MemoryStorage()) dp.middleware.setup( I18nMiddleware( bot=bot, # Mapping 'en-US' and 'en-GB' to 'en' locale_map={'en-US': 'en', 'en-GB': 'en'} ) ) # ... other setup and handlers ... await dp.start_polling() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Creating ReplyKeyboardMarkup with LazyTranslated Buttons Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/3-lazy-proxy.md Example of constructing a ReplyKeyboardMarkup where each button's text is a LazyProxy. The translations are applied when the keyboard is sent. ```python from aiogram_i18n import LazyProxy from aiogram_i18n.types import KeyboardButton, ReplyKeyboardMarkup # Create keyboard with lazy-translated buttons keyboard = ReplyKeyboardMarkup( keyboard=[ [KeyboardButton(text=LazyProxy("menu.start"))], [KeyboardButton(text=LazyProxy("menu.help"))], [KeyboardButton(text=LazyProxy("menu.settings"))], ], resize_keyboard=True ) # The buttons will be translated when the keyboard is serialized/sent ``` -------------------------------- ### Use LazyFilter in a Message Handler Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/5-lazy-filter.md Integrate LazyFilter directly into an aiogram message handler to filter incoming messages based on translated text. This example shows a basic handler for a single menu start key. ```python from aiogram import Router from aiogram.types import Message from aiogram_i18n import LazyFilter router = Router() # Use filter with handler @router.message(LazyFilter("menu.start")) async def start_handler(message: Message): await message.reply("Starting...") ``` -------------------------------- ### FSMManager Setup Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Configure FSMManager for locale management within finite state machines. Allows customization of the FSM state data key and default locale. ```python from aiogram_i18n.managers.fsm import FSMManager # Simple setup manager = FSMManager() # Custom key manager = FSMManager(key="user_language", default_locale="en") ``` -------------------------------- ### Attribute-Based Access Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Shows how to access translation strings using attribute-like notation, which can make the code more readable for simple translations. ```python from aiogram import types @dp.message_handler() async def echo_handler(message: types.Message): # Accessing translation using attribute-like syntax await message.answer(message.from_user.i18n.greeting) ``` -------------------------------- ### Register Startup Handler with I18nMiddleware Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/2-i18n-middleware.md Registers an asynchronous function to be called during dispatcher startup using the @middleware.on_startup decorator. The function receives the I18nContext and dispatcher, allowing for translation-related setup. ```python @middleware.on_startup async def init_translations(i18n: I18nContext, dispatcher: Dispatcher): # Initialize translation-related setup print(f"Available locales: {i18n.core.available_locales}") ``` -------------------------------- ### Simple Translation Retrieval Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Demonstrates the most basic usage of retrieving a translated string using the I18nContext object within a handler. ```python from aiogram import types from aiogram.dispatcher.filters import CommandStart @dp.message_handler(CommandStart()) async def start_handler(message: types.Message): # Accessing the I18nContext from the message object # and retrieving a simple translation await message.answer(message.from_user.i18n.get('welcome')) ``` -------------------------------- ### Minimal I18nMiddleware Configuration Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/13-index.md Basic configuration for the I18nMiddleware using FluentRuntimeCore. This setup requires a 'locales' directory with language-specific message files. ```python middleware = I18nMiddleware( core=FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES") ) ``` -------------------------------- ### Getting Reply Markup for Language Selection Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/9-language-inline-keyboard.md Illustrates how to obtain the InlineKeyboardMarkup for language selection using the reply_markup method. This keyboard can then be sent with a message to allow users to choose their language. ```python from aiogram.types import Message from aiogram_i18n import I18nContext async def language_handler(message: Message, i18n: I18nContext): keyboard = lang_markup.reply_markup(locale=i18n.locale) await message.reply( text="Select your language:", reply_markup=keyboard ) ``` -------------------------------- ### LanguageInlineMarkup Startup Initialization Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/9-language-inline-keyboard.md Shows how to initialize the LanguageInlineMarkup by calling its startup method with an I18nContext. This populates the keyboard with available locales and their localized names. ```python from aiogram_i18n import I18nContext from aiogram_i18n.utils.language_inline_keyboard import LanguageInlineMarkup lang_markup = LanguageInlineMarkup(key="languages.name") await lang_markup.startup(i18n) # Now lang_markup.keyboards is populated ``` -------------------------------- ### LanguageInlineMarkup Constructor Examples Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/9-language-inline-keyboard.md Demonstrates simple and custom configurations for initializing the LanguageInlineMarkup class. Specify the translation key for button labels and optionally customize rows, hiding the current locale, and callback data prefix. ```python from aiogram_i18n.utils.language_inline_keyboard import LanguageInlineMarkup # Simple usage with defaults lang_markup = LanguageInlineMarkup(key="languages.name") # Custom configuration lang_markup = LanguageInlineMarkup( key="language.label", row=2, hide_current=True, prefix="select_lang" ) ``` -------------------------------- ### Initializing AttrDict Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/12-attr-dict.md Demonstrates how to create an instance of AttrDict by wrapping a standard Python dictionary. ```python from aiogram_i18n.utils.attrdict import AttrDict data = {"name": "Alice", "age": 30} attr_dict = AttrDict(data) ``` -------------------------------- ### Initialize I18nContext Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/1-i18n-context.md Instantiate I18nContext with locale, core, manager, and user data. The key_separator is optional. ```python from aiogram_i18n import I18nContext from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.managers.memory import MemoryManager core = FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES") manager = MemoryManager(default_locale="en") context = I18nContext( locale="en", core=core, manager=manager, data={}, key_separator="-" ) ``` -------------------------------- ### BaseCore get Method Signature Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Signature for the 'get' method in BaseCore, used for retrieving translated messages with optional interpolation variables. ```python def get(message: str, locale: str | None = None, /, **kwargs: Any) -> str ``` -------------------------------- ### __call__ Method (Alias for get) Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/1-i18n-context.md Alias for the get() method, allowing the context object to be used directly as a callable for retrieving translations. ```APIDOC ## __call__ Method ### Description Alias for the `get()` method. Allows using the context object directly as a callable. ### Method __call__ ### Parameters #### Path Parameters - **key** (str) - Required - Translation message key - **locale** (str | None) - Optional - Target locale; if None, uses the context's current locale #### Query Parameters - **kwargs** (Any) - Optional - Variables for interpolation in the translation ### Response - **str** - The translated and interpolated message string ### Example: ```python # Equivalent to context.get("greeting") text = context("greeting") # With interpolation text = context("welcome", user_name="Alice") ``` ``` -------------------------------- ### Basic aiogram bot with i18n Source: https://github.com/aiogram/i18n/blob/dev/README.md This example demonstrates setting up an aiogram bot with aiogram_i18n using FluentRuntimeCore. It includes message handlers for the /start command and a lazy filter for 'help'. Ensure your locale files are in the specified path. ```python import asyncio from contextlib import suppress from logging import basicConfig, INFO from typing import Any from aiogram import Router, Dispatcher, Bot from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode from aiogram.filters import CommandStart from aiogram.types import Message from aiogram_i18n import I18nContext, LazyProxy, I18nMiddleware, LazyFilter from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore from aiogram_i18n.types import ( ReplyKeyboardMarkup, KeyboardButton # you should import mutable objects from here if you want to use LazyProxy in them ) router = Router(name=__name__) rkb = ReplyKeyboardMarkup( keyboard=[ [KeyboardButton(text=LazyProxy("help"))] # or L.help() ], resize_keyboard=True ) @router.message(CommandStart()) async def cmd_start(message: Message, i18n: I18nContext) -> Any: name = message.from_user.mention_html() return message.reply( text=i18n.get("hello", user=name), # or i18n.hello(user=name) reply_markup=rkb ) @router.message(LazyFilter("help")) # or LazyProxy("help") or F.text == LazyProxy("help") async def cmd_help(message: Message) -> Any: return message.reply(text="-- " + message.text + " --") async def main() -> None: basicConfig(level=INFO) bot = Bot("42:ABC", default=DefaultBotProperties(parse_mode=ParseMode.HTML)) i18n_middleware = I18nMiddleware( core=FluentRuntimeCore( path="locales/{locale}/LC_MESSAGES" ) ) dp = Dispatcher() dp.include_router(router) i18n_middleware.setup(dispatcher=dp) await dp.start_polling(bot) if __name__ == "__main__": with suppress(KeyboardInterrupt): asyncio.run(main()) ``` -------------------------------- ### Variable Interpolation Example Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/COMPLETION_SUMMARY.txt Illustrates how to use variable interpolation within translations to personalize messages. This example shows inserting a username into a greeting. ```python from aiogram import types from aiogram.dispatcher.filters import CommandStart @dp.message_handler(CommandStart()) async def start_handler(message: types.Message): # Translating a string with a variable (username) await message.answer(message.from_user.i18n.get('welcome_user', username=message.from_user.username)) ``` -------------------------------- ### Example Usage of NoTranslateFileExistsError Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/8-exceptions.md Illustrates catching `NoTranslateFileExistsError` when translation files are missing. This example assumes a specific directory structure and core initialization. ```python # Directory structure: # locales/ # en/ (empty or no matching files) # fr/ (empty) from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore try: core = FluentRuntimeCore(path="locales/{locale}/LC_MESSAGES") except NoTranslateFileExistsError as e: # files with extension (.ftl)in folder (locales/en/LC_MESSAGES) not found print(e) ``` -------------------------------- ### Example Usage of NoLocalesFoundError Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/8-exceptions.md Demonstrates catching `NoLocalesFoundError` when no locale directories are found. This example assumes a directory structure where the base path contains no subdirectories for locales. ```python # Directory structure: # translations/ (no subdirectories) from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore try: core = FluentRuntimeCore(path="translations/{locale}") except NoLocalesFoundError as e: # locales ([]) in path (translations) not found print(e) ``` -------------------------------- ### Chained Attribute Access vs. MagicProxy Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/4-lazy-factory.md Illustrates the difference between accessing an attribute to get a MagicProxy and calling it to get a LazyProxy. MagicProxy supports further chaining, while LazyProxy represents the final translation key. ```python from aiogram_i18n import L # These are equivalent: # L.menu.start() → LazyProxy("menu-start") # L.menu.start() → factory("menu-start") lazy = L.menu.start print(lazy) # lazy_proxy = L.menu.start() print(lazy_proxy) # ``` -------------------------------- ### Creating LazyProxy Instances Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/3-lazy-proxy.md Demonstrates how to create LazyProxy objects for simple translations, translations with interpolation, and translations for a specific locale. ```python from aiogram_i18n import LazyProxy # Simple lazy translation button_text = LazyProxy("menu.start") # With interpolation parameters welcome_text = LazyProxy("welcome", user_name="Alice", count=5) # With specific locale french_text = LazyProxy("greeting", locale="fr") ``` -------------------------------- ### Claude Settings.json Configuration Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/14-configuration-reference.md Example configuration for `.claude/settings.json` to use aiogram_i18n patterns. ```json { "model": "claude-opus-4-8", "custom_instructions": "Always use aiogram_i18n patterns" } ``` -------------------------------- ### FluentCompileCore Constructor Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Illustrates the constructor for FluentCompileCore, detailing its parameters for path, default locale, isolation, custom functions, error handling, text decoration, and locale mappings. ```python def __init__( self, path: str | Path, default_locale: str | None = None, use_isolating: bool = False, functions: dict[str, Callable[..., Any]] | None = None, raise_key_error: bool = True, use_td: bool = True, locales_map: dict[str, str] | None = None, ) -> None ``` -------------------------------- ### Handling Optional Dependencies with Try-Except Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/8-exceptions.md Shows a best practice for handling optional dependencies by attempting to import a core and falling back to another if the module is not found. ```python try: from aiogram_i18n.cores.fluent_runtime_core import FluentRuntimeCore except NoModuleError as e: print(f"Install dependencies: {e}") # Gracefully fall back to another core from aiogram_i18n.cores.gnu_text_core import GNUTextCore core = GNUTextCore(path="locales/{locale}/LC_MESSAGES") ``` -------------------------------- ### BaseCore startup Method Signature Source: https://github.com/aiogram/i18n/blob/dev/_autodocs/6-translation-cores.md Signature for the asynchronous 'startup' method in BaseCore, which is called during dispatcher startup to load translation locales. ```python async def startup() -> None ```