Introduction
In this article, I’ll show you how I create multilingual Telegram bots using `aiogram` and the `Babel` package.
That said, every bot I build is translated into at least English, so you can check out any of them for a closer look. `TextifyPic_bot` is the simplest one to start with, while `NotebookOnMarginalia_bot` is a good choice for a more advanced example.
Translations
Locating the necessary strings
Each string needs to be wrapped in the underscore alias. To do this, we import the corresponding module for the bot, and initialize some global variables :
Extracting strings
Once all the necessary strings have been selected, you can begin extracting them to the locales directory. All strings and their associated data will be saved in the messages.pot file.
Locale initialization
You need to create exactly as many locales as the number of languages you intend to use. In my case, there are two, and they are created like this:
Performing the translation
Once the required locales have been initialized, you can proceed to the actual translation. This means opening the generated .po files and entering the translations.
Compiling translations
Now, let's compile the translations. We will need to generate special .mo files.
Now, when a user with a different language setting visits the bot, the correct strings will be displayed. However, if you need to fix or update translations, a slightly different process is used.
Updating translations
First, we extract the changes from all the translation files.
Afterwards we update all locales
We update/fix the translations. And finally, we compile the translations:
That’s it - the translations have been updated.
Conclusion
Creating translations for Telegram bots isn't exactly simple and can be quite a headache for someone doing it for the first time.
The main thing is to grasp the initialization process:
- Wrap the necessary strings.
- Extract all wrapped strings into a single master file.
- Initialize the required locales (languages).
- Translate.
- Compile.
To update the translations:
- Extract all wrapped strings into a single master file.
- Update the existing locales.
- Translate.
- Compile.
In my opinion, the most difficult step is likely the translation itself; the rest is just a matter of procedure.