You need to:
1) wrap your code in a specific block that reacts to incoming messages
2) configure Messages.app to invoke your script for incoming messages
For the first, copy the entire following script and put your code in place where it says 'YOUR CODE HERE':
using terms from application "Messages"
on message receivedtheMessagefromtheBuddyfortheChat
-- YOUR CODE HERE
end message received
on received text invitationtheTextfromtheBuddyfortheChat
accepttheChat
end received text invitation
on received audio invitationtheTextfromtheBuddyfortheChat
accepttheChat
end received audio invitation
on received video invitationtheTextfromtheBuddyfortheChat
accepttheChat
end received video invitation
on received file transfer invitationtheFileTransfer
accepttheFileTransfer
end received file transfer invitation
on buddy authorization requestedtheRequest
accepttheRequest
end buddy authorization requested
# The following are unused but need to be defined to avoid an error
on message senttheMessagefortheChat
end message sent
on chat room message receivedtheMessagefromtheBuddyfortheChat
end chat room message received
on active chat message receivedtheMessage
end active chat message received
on addressed chat room message receivedtheMessagefromtheBuddyfortheChat
end addressed chat room message received
on addressed message receivedtheMessagefromtheBuddyfortheChat
end addressed message received
on av chat started
end av chat started
on av chat ended
end av chat ended
on login finishedfortheService
end login finished
on logout finishedfortheService
end logout finished
on buddy became availabletheBuddy
end buddy became available
on buddy became unavailabletheBuddy
end buddy became unavailable
on completed file transfer
end completed file transfer
end using terms from
The rest of the code is irrelevant for your needs, but is required to prevent Messages.app from choking on your script not knowing how to deal with events.
Next, save your script in ~/Library/Application Scripts/com.apple.iChat
It will now appear in Messages' preferences, under the 'AppleScript handler' option.
Now, for any event, Messages will invoke the appropriate handler in your script.