This script doesn't work because the events "on disconnect" and "on exit" trigger
after you have disconnected from the server, so you can't start sending messages to channels as if you're connected.
To get around this define your own /exit alias, with /exit (the built-in command) at the end:
alias exit {
msg #chan text
do stuff
exit
}
And the next time you want to close mIRC, type /exit, and all the necessary stuff will be done before exiting.