11import contextvars
2+ import gettext
3+ import os
4+
5+ from telebot .asyncio_handler_backends import BaseMiddleware
26
37try :
48 from babel .support import LazyProxy
711except ImportError :
812 babel_imported = False
913
10- from telebot import util
11-
12-
13- class BaseMiddleware :
14- """
15- Base class for middleware.
16-
17- Your middlewares should be inherited from this class.
18- """
19-
20- def __init__ (self ):
21- pass
22-
23- async def pre_process (self , message , data ):
24- raise NotImplementedError
25-
26- async def post_process (self , message , data , exception ):
27- raise NotImplementedError
28-
2914
3015class I18N (BaseMiddleware ):
3116 """
@@ -41,7 +26,7 @@ def __init__(self, translations_path, domain_name: str):
4126
4227 self .path = translations_path
4328 self .domain = domain_name
44- self .translations = util .find_translations (self . path , self . domain )
29+ self .translations = self .find_translations ()
4530
4631 @property
4732 def available_translations (self ):
@@ -107,3 +92,29 @@ async def pre_process(self, message, data):
10792
10893 async def post_process (self , message , data , exception ):
10994 pass
95+
96+ def find_translations (self ):
97+ """
98+ Looks for translations with passed 'domain' in passed 'path'
99+ """
100+ if not os .path .exists (self .path ):
101+ raise RuntimeError (f"Translations directory by path: { self .path !r} was not found" )
102+
103+ result = {}
104+
105+ for name in os .listdir (self .path ):
106+ translations_path = os .path .join (self .path , name , 'LC_MESSAGES' )
107+
108+ if not os .path .isdir (translations_path ):
109+ continue
110+
111+ po_file = os .path .join (translations_path , self .domain + '.po' )
112+ mo_file = po_file [:- 2 ] + 'mo'
113+
114+ if os .path .isfile (po_file ) and not os .path .isfile (mo_file ):
115+ raise FileNotFoundError (f"Translations for: { name !r} were not compiled!" )
116+
117+ with open (mo_file , 'rb' ) as file :
118+ result [name ] = gettext .GNUTranslations (file )
119+
120+ return result
0 commit comments