· 5 years ago · Sep 28, 2020, 03:12 PM
1import json
2import os
3from pathlib import Path
4
5from aiogram import types
6from aiogram.dispatcher.middlewares import BaseMiddleware
7
8
9class LocaleMiddleware(BaseMiddleware):
10 """
11 Интернационализация бота
12 """
13
14 def __init__(self, api=None, path=None):
15 super().__init__()
16 if path is None:
17 path = os.path.join(os.getcwd(), 'bot', 'locales')
18 self.path = path
19 self.locales = self.load_locales()
20 self.language_code = 'ru'
21 self.api = api
22
23 def load_locales(self) -> dict:
24 """
25 Поиск и загрузка языков
26 """
27 result = {}
28
29 for name in os.listdir(self.path):
30 if os.path.isdir(os.path.join(self.path, name)):
31 continue
32
33 key = name.split('.')[0]
34 locale_path = os.path.join(self.path, name)
35 with open(locale_path, 'r') as file:
36 data = json.load(file)
37
38 result.update({key: data})
39
40 return result
41
42 def get_text(self, key):
43 """
44 Перевод текста
45 """
46 locale = self.locales.get(self.language_code)
47 return locale.get(key)
48
49 async def get_user_locale(self, action: str, args) -> str:
50 """
51 Определяем язык для пользователя
52 """
53 user = types.User.get_current()
54 language_code = self.api.get_language(
55 user.id) or user.language_code
56 return language_code
57
58 async def trigger(self, action, args):
59 """
60 Event trigger
61 :param action: event name
62 :param args: event arguments
63 :return:
64 """
65 if 'update' not in action \
66 and 'error' not in action \
67 and action.startswith('pre_process'):
68 self.language_code = await self.get_user_locale(action, args)
69 return True
70