Our bot example will consist of 2 *.py files, main.pyand config.py. The first will contain the entry point and the corresponding handlers, and the second will contain the settings for translations. The code for the example was taken from the Bot-example for connecting the Inline mode.
Necessary code and setup
As I promised, we do translations. Firstly, create a locales directory in the project folder. Then add the following imports to the main.py file:
In the config.py file, we will set up a directory for storing translations and middleware, respectively.
Marking strings for translation
After we have connected the relevant modules and set up the environment, we need to mark which strings we are going to translate. In main.py I created an alias.
Each line will need to be wrapped around the alias of gettext. The end result will look something like this:
Extracting strings
Finally, you can start extracting strings to the locales folder. All strings and their data will be saved in the messages.pot file.
Initializing locales and translated languages
You will need to make exactly as many locales as languages you are going to use. In my case, there are 2, and they are made like this:
Translate
The first is English, the second is Russian. In the first case, after generation, you will need to write a translation. You will need to find the messages.po file in locales\en\LC_MESSAGES and write translations. In the second case, this is the original language. No need to do translations.
Compiling translations
Now let's compile the translations
Updating translations
The translations are ready. But what if you wanted to make changes to the translations or added another text? In this case, you need to update the translations. And to do this, you will have to perform slightly different steps than when initializing in the first steps.
It is important to remember that we initialize only once. Then, unless you want to lose all the translations, you will need to update them in a special way. First, extract the changes from all files with translation strings.
Afterward, we update all locales
And finally compile the translations.
That's it, the translations have been updated and will be shown depending on the user's Telegram client settings.
Conclusion
Translations for bots in Telegram are not so easy and can cause quite a headache for those who do it for the first time. The most difficult step, in my opinion, is finding and wrapping the lines you need for translation. Because not all lines can be wrapped, but if you follow the basic rules, everything should work out. ( ̄︶ ̄)↗