refactor
refactor
handle_messages function