BaseMiddleware returned to it's original place && I18N middleware is now only in examples

This commit is contained in:
abdullaev388 2022-02-20 00:08:14 +05:00
parent 9b20f41ece
commit 74e9780b30
5 changed files with 50 additions and 27 deletions

View File

@ -1,6 +1,6 @@
# Just a little example of middleware handlers
from telebot.asyncio_middlewares import BaseMiddleware
from telebot.asyncio_handler_backends import BaseMiddleware
from telebot.async_telebot import AsyncTeleBot
from telebot.async_telebot import CancelUpdate
bot = AsyncTeleBot('TOKEN')

View File

@ -7,7 +7,6 @@
# But this example just to show the work of middlewares.
import telebot
import telebot.asyncio_middlewares
from telebot.async_telebot import AsyncTeleBot
from telebot import asyncio_handler_backends
import logging
@ -28,7 +27,7 @@ TRANSLATIONS = {
bot = AsyncTeleBot('TOKEN')
class LanguageMiddleware(telebot.asyncio_middlewares.BaseMiddleware):
class LanguageMiddleware(asyncio_handler_backends.BaseMiddleware):
def __init__(self):
self.update_types = ['message'] # Update types that will be handled by this middleware.
async def pre_process(self, message, data):

View File

@ -1,4 +1,8 @@
import contextvars
import gettext
import os
from telebot.asyncio_handler_backends import BaseMiddleware
try:
from babel.support import LazyProxy
@ -7,25 +11,6 @@ try:
except ImportError:
babel_imported = False
from telebot import util
class BaseMiddleware:
"""
Base class for middleware.
Your middlewares should be inherited from this class.
"""
def __init__(self):
pass
async def pre_process(self, message, data):
raise NotImplementedError
async def post_process(self, message, data, exception):
raise NotImplementedError
class I18N(BaseMiddleware):
"""
@ -41,7 +26,7 @@ class I18N(BaseMiddleware):
self.path = translations_path
self.domain = domain_name
self.translations = util.find_translations(self.path, self.domain)
self.translations = self.find_translations()
@property
def available_translations(self):
@ -107,3 +92,29 @@ class I18N(BaseMiddleware):
async def post_process(self, message, data, exception):
pass
def find_translations(self):
"""
Looks for translations with passed 'domain' in passed 'path'
"""
if not os.path.exists(self.path):
raise RuntimeError(f"Translations directory by path: {self.path!r} was not found")
result = {}
for name in os.listdir(self.path):
translations_path = os.path.join(self.path, name, 'LC_MESSAGES')
if not os.path.isdir(translations_path):
continue
po_file = os.path.join(translations_path, self.domain + '.po')
mo_file = po_file[:-2] + 'mo'
if os.path.isfile(po_file) and not os.path.isfile(mo_file):
raise FileNotFoundError(f"Translations for: {name!r} were not compiled!")
with open(mo_file, 'rb') as file:
result[name] = gettext.GNUTranslations(file)
return result

View File

@ -56,7 +56,7 @@ import keyboards
from telebot import types
from telebot.async_telebot import AsyncTeleBot
from telebot.asyncio_filters import TextMatchFilter, TextFilter
from telebot.asyncio_middlewares import I18N
from i18n_base_midddleware import I18N
from telebot.asyncio_storage.memory_storage import StateMemoryStorage
@ -87,7 +87,7 @@ class I18NMiddleware(I18N):
storage = StateMemoryStorage()
bot = AsyncTeleBot("", state_storage=storage)
bot = AsyncTeleBot("1254795383:AAE7gbj1aas4lEDHB1eVuZZhSGPWcH1B5ds", state_storage=storage)
i18n = I18NMiddleware(translations_path='locales', domain_name='messages')
_ = i18n.gettext # for singular translations

View File

@ -1,4 +1,17 @@
from telebot.asyncio_middlewares import BaseMiddleware
class BaseMiddleware:
"""
Base class for middleware.
Your middlewares should be inherited from this class.
"""
def __init__(self):
pass
async def pre_process(self, message, data):
raise NotImplementedError
async def post_process(self, message, data, exception):
raise NotImplementedError
class State:
@ -15,4 +28,4 @@ class StatesGroup:
for name, value in cls.__dict__.items():
if not name.startswith('__') and not callable(value) and isinstance(value, State):
# change value of that variable
value.name = ':'.join((cls.__name__, name))
value.name = ':'.join((cls.__name__, name))