Search code examples
pythonaiogram

Handle message again aiogram


I need to replace 1 special character in the message

I have this function

@dp.message_handler(Text(contains='-g'))
async def g_replace(message: types.Message):
    message.text = message.text.lower().replace('-g', '').replace('г', 'ґ')
    # handle message again

After that I want to handle this message again with other handlers. Is it possible?

UPD: I don't want to handle message with the same handler, so I need the same result as if user have sent modified message. So I can't use constructions like other_handler(message) or this_handler(message) because I don't know exactly which handler would handle that message


Solution

  • I have solved this problem with middlewares, wich are somthing like handlers before handlers. First of all - import middleware class:

    from aiogram.dispatcher.middlewares import BaseMiddleware
    

    After that, define class for middleware

    class GPreFilter(BaseMiddleware):
    def __init__(self):
        super(GPreFilter, self).__init__()
    
    async def on_process_message(self, message: types.Message, *args):
        if '-g' in message.text.lower():
            message.text = message.text.lower().replace('-g', '').replace('г', 'ґ')
    

    Aiogram automatically calls on_process_message when it is a new message. Then setup this middleware

    dp.middleware.setup(GPreFilter())
    

    Now all the messages will be handled by middleware, and then by handlers