Refactor the _on_message function, split everything out into separate functions