username = '******' await bot.send_message(message.chat.id, username) # You can make it case insensitive @bot.message_handler(text=TextFilter(equals=l_("My first name"), ignore_case=True)) async def return_user_id(message: types.Message): await bot.send_message(message.chat.id, message.from_user.first_name) all_menu_texts = [] for language in i18n.available_translations: for menu_text in ("My user id", "My user name", "My first name"): all_menu_texts.append(_(menu_text, language)) # When user confused language. (handles all menu buttons texts) @bot.message_handler(text=TextFilter(contains=all_menu_texts, ignore_case=True)) async def missed_message(message: types.Message): await bot.send_message(message.chat.id, _("Seems you confused language"), reply_markup=keyboards.menu_keyboard(_)) if __name__ == '__main__': bot.setup_middleware(i18n) bot.add_custom_filter(TextMatchFilter()) asyncio.run(bot.infinity_polling())
def __init__(self, limit) -> None: self.last_time = {} self.limit = limit self.update_types = ['message'] # Always specify update types, otherwise middlewares won't work async def pre_process(self, message, data): if not message.from_user.id in self.last_time: # User is not in a dict, so lets add and cancel this function self.last_time[message.from_user.id] = message.date return if message.date - self.last_time[message.from_user.id] < self.limit: # User is flooding await bot.send_message(message.chat.id, 'You are making request too often') return CancelUpdate() self.last_time[message.from_user.id] = message.date async def post_process(self, message, data, exception): pass bot.setup_middleware(SimpleMiddleware(2)) @bot.message_handler(commands=['start']) async def start(message): await bot.send_message(message.chat.id, 'Hello!') import asyncio asyncio.run(bot.polling())
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): data['response'] = TRANSLATIONS['hello'][ message.from_user.language_code] async def post_process(self, message, data, exception): if exception: # You can get exception occured in handler. logger.exception(str(exception)) bot.setup_middleware(LanguageMiddleware()) # do not forget to setup @bot.message_handler(commands=['start']) async def start(message, data: dict): # you can get the data in handler too. # Not necessary to create data parameter in handler function. await bot.send_message(message.chat.id, data['response']) import asyncio asyncio.run(bot.polling())